I'm developing a web application for a handheld RFID reader (windows CE),
and I'm trying to send an XML file from the RFID reader to a laptop throgh wireless network or GPRS. The code works properly with "windows form application" on MS visual studio, but when I try to use it with "smart device application" it doesn't work... an error appears for the "ReadAllBytes" method:
System.IO.File dose not contain a definition for ReadAllBytes
Please help me to handle this error.
Thanks.
The code:
private void button1_Click(object sender, EventArgs e)
{
try
{
string IpAddressString = "10.1.1.104";
IPEndPoint ipEnd_client = new
IPEndPoint(IPAddress.Parse(IpAddressString), 5656);
Socket clientSock_client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.IP);
string fileName = "student.XML";
string filePath =#"My Device\";
fileName = fileName.Replace("\\", "/");
while (fileName.IndexOf("/") > -1)
{
filePath += fileName.Substring(0, fileName.IndexOf("/") + 1);
fileName = fileName.Substring(fileName.IndexOf("/") + 1);
}
byte[] fileNameByte = Encoding.UTF8.GetBytes(fileName);
if (fileNameByte.Length > 5000 * 1024)
{
curMsg_client = "File size is more than 5Mb,
please try with small file.";
MessageBox.Show("File size is more than 5Mb,
please try with small file.");
return;
}
MessageBox.Show("Buffering ...");
string fullPath = filePath + fileName;
byte[] fileData =File.ReadAllBytes(fullPath);
byte[] clientData = new byte[4 + fileNameByte.Length +
fileData.Length];
//byte[] clientData = new byte[4 + fileNameByte.Length];
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
fileNameLen.CopyTo(clientData, 0);
fileNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fileNameByte.Length);
MessageBox.Show("Connection to server ...");
clientSock_client.Connect(ipEnd_client);
MessageBox.Show("File sending...");
clientSock_client.Send(clientData, 0, clientData.Length, 0);
MessageBox.Show("Disconnecting...");
clientSock_client.Close();
MessageBox.Show ("File [" + fullPath + "] transferred.");
}
catch (Exception ex)
{
if (ex.Message == "No connection could be made
because the target machine actively refused it")
{
MessageBox.Show ("File Sending fail. Because
server not running.");
}
else
{
MessageBox.Show ("File Sending fail." +
ex.Message.ToString());
}
}
}
It's because, as the error states, ReadAllBytes doesn't exist in the Compact Framework. You have to use an overload of Read to get the data.
Something along these lines:
using (var reader = File.OpenRead(filePath))
{
var fileData = new byte[reader.Length];
reader.Read(fileData, 0, fileData.Length);
}
Related
I am working on a unity project where user can send data from client to server using TCP/IP. I am able to send the data. But my unity stalls or freeze until the data got read from the networkstream.
Server Code:Read Data.
public void StartServer (){
// Start TcpServer background thread
tcpListenerThread = new Thread (new ThreadStart(ListenForIncomingRequests));
tcpListenerThread.IsBackground = true;
tcpListenerThread.Start();
startServerButton.interactable = false;
path = UnityEditor.EditorUtility.SaveFolderPanel ("Any type of File.", "", ""); // Path.Combine(path,"D:\\Siva\\TCPDownloadfiles");
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Space)) {
SendMessage();
}
}
/// <summary>
/// Runs in background TcpServerThread; Handles incoming TcpClient requests
/// </summary>
private void ListenForIncomingRequests () {
Thread threadForDownloading = new Thread (new ThreadStart(DownloadingStreamData));
threadForDownloading.IsBackground = true;
threadForDownloading.Start();
//DownloadingStreamData ();
}
private void DownloadingStreamData()
{
try {
fileCount++;
int fileNameLen;
byte[] incomingData = new byte[1024];
string ext = "";
// Create listener on localhost port 8052.
tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8052);
tcpListener.Start();
Debug.Log("Server is listening");
bytes = new Byte[Int32.MaxValue]; // 2221024
while (true) {
using (connectedTcpClient = tcpListener.AcceptTcpClient()) {
// Get a stream object for reading
using (stream = connectedTcpClient.GetStream()) {
Debug.Log("Befor Stream Read..........");
IAsyncResult result = stream.BeginRead(bytes, 0, bytes.Length, MessageReceived, stream);
result.AsyncWaitHandle.WaitOne();
// Read incoming stream into byte arrary.
do{
//length = stream.Read(bytes, 0, bytes.Length);
//length = s_bytesReceived;
Debug.Log("After Stream Read.........."+length);
incomingData = new byte[length];
Array.Copy(bytes, 0, incomingData, 0, length - 4);
// Convert byte array to string message.
fileNameLen = BitConverter.ToInt32(incomingData, 0);
string clientMessage = Encoding.ASCII.GetString(incomingData,4, fileNameLen);
ext = Path.GetExtension(clientMessage);
//Debug.Log("client message received as: " + clientMessage);
//File.WriteAllBytes(path + "\\temp"+fileCount.ToString()+ext, incomingData);
BinaryWriter bWrite = new BinaryWriter(File.Open(path + "\\temp"+fileCount.ToString()+ext, FileMode.Create)); ;
bWrite.Write(incomingData, 4 + fileNameLen, length - 4 - fileNameLen);
bWrite.Flush();
bWrite.Close();
} while(stream.DataAvailable);
//Debug.Log("Bytes length2 :>>>"+" "+fileNameLen +" Incoming data length" +incomingData.Length);
//connectedTcpClient.Close();
//stream.Flush();
//stream.Close();
//Debug.Log("GETTING FILE NAME THROUGH BUFFER ::"+stream);
}
}
}
}
catch (SocketException socketException) {
Debug.Log("SocketException " + socketException.ToString());
}
}
I tried using stream.BeginRead method but that is throwing exception like Stream/socket was disposed already and trying to access it on client code.
But stream.Read method works as like i expect but it stalls/freeze the unity until it get the data.Please give me some better solution for this issue. Thanks in advance.
Client Code: Sends Data
if (stream.CanWrite) {
string path = UnityEditor.EditorUtility.OpenFilePanel ("Any type of File.", "", "");
WWW www = new WWW ("file:///" + path);
byte[] fileNameBytes = Encoding.ASCII.GetBytes(path);
byte[] fileDataBytes = www.bytes;
byte[] fileNameLength = BitConverter.GetBytes(fileNameBytes.Length);
clientData = new byte[4 + fileNameBytes.Length + fileDataBytes.Length];
fileNameLength.CopyTo(clientData, 0);
fileNameBytes.CopyTo(clientData, 4);
fileDataBytes.CopyTo(clientData, 4 + fileNameBytes.Length);
Debug.Log ("FIle sends to server path : "+path);
//stream.BeginRead(clientData, 0, clientData.Length, MessageReceived, stream);
try {
stream.Write(clientData, 0, clientData.Length);
//stream.BeginWrite(clientData, 0, clientData.Length, MessageReceived, stream);
}catch (Exception e) {
Debug.Log("SocketException " + e.ToString());
}
I am trying to download a file usng FTP within a C# console application, but even though I now the paths are correct I always get an error saying "550 file not found".
Is there any way, to return the current path (once connected to the server)?
// lade datei von FTP server
string ftpfullpath = "ftp://" + Properties.Settings.Default.FTP_Server + Properties.Settings.Default.FTP_Pfad + "/" + Properties.Settings.Default.FTP_Dateiname;
Console.WriteLine("Starte Download von: " + ftpfullpath);
using (WebClient request = new WebClient())
{
request.Credentials = new NetworkCredential(Properties.Settings.Default.FTP_User, Properties.Settings.Default.FTP_Passwort);
byte[] fileData = request.DownloadData(ftpfullpath);
using (FileStream file = File.Create(#path + "/tmp/" + Properties.Settings.Default.FTP_Dateiname))
{
file.Write(fileData, 0, fileData.Length);
file.Close();
}
Console.WriteLine("Download abgeschlossen!");
}
EDIT
My mistake. Fixed the filepath, still getting the same error. But if I connect with FileZilla that's the exact file path.
Finally found a solution by using System.Net.FtpClient (https://netftp.codeplex.com/releases/view/95632) and using the following code.
// aktueller pfad
string apppath = Directory.GetCurrentDirectory();
Console.WriteLine("Bereite Download von FTP Server vor!");
using (var ftpClient = new FtpClient())
{
ftpClient.Host = Properties.Settings.Default.FTP_Server;
ftpClient.Credentials = new NetworkCredential(Properties.Settings.Default.FTP_User, Properties.Settings.Default.FTP_Passwort);
var destinationDirectory = apppath + "\\Input";
ftpClient.Connect();
var destinationPath = string.Format(#"{0}\{1}", destinationDirectory, Properties.Settings.Default.FTP_Dateiname);
Console.WriteLine("Starte Download von " + Properties.Settings.Default.FTP_Dateiname + " nach " + destinationPath);
using (var ftpStream = ftpClient.OpenRead(Properties.Settings.Default.FTP_Pfad + "/" + Properties.Settings.Default.FTP_Dateiname))
using (var fileStream = File.Create(destinationPath , (int)ftpStream.Length))
{
var buffer = new byte[8 * 1024];
int count;
while ((count = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, count);
}
}
}
I think your filename is wrong. Your first line writes a different name than what you set to ftpfullpath. You us FTP_Dateiname on the first line but FTP_Pfad when you set ftpfullpath.
To see what's actually happening move your first line after 'string ftpfullpath...')
and change it to Console.WriteLine("Starte Download von: " + ftpfullpath);
I wrote that code after some research on the internet to send files throught computers at the same network. But, sometimes it's sending the files corrupted or with low quality (if the file is a picture). Can you check this out?
Note: I want to send only files with 10MB size.
Server
class Server
{
IPEndPoint end;
Socket sock;
public Server()
{
end = new IPEndPoint(IPAddress.Any, 5656);
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(end);
}
public static string path;
public static string MsgCurrent = "Stopped";
public void StartServer()
{
try
{
MsgCurrent = "Starting...";
sock.Listen(100);
MsgCurrent = "Works and looks for files";
Socket clientSock = sock.Accept();
byte[] clientData = new byte[1024 * 1024 * 10]; //count per byte
int receivedByteLen = clientSock.Receive(clientData);
MsgCurrent = "Receiving file ...";
int fNameLen = BitConverter.ToInt32(clientData, 0);
string fName = Encoding.ASCII.GetString(clientData, 4, fNameLen);
BinaryWriter write = new BinaryWriter(File.Open(path + "/" + fName, FileMode.Append));
write.Write(clientData, 4 + fNameLen, receivedByteLen - 4 - fNameLen);
MsgCurrent = "Saving file....";
write.Close();
clientSock.Close();
MsgCurrent = "The file was received";
}
catch
{
MsgCurrent = "Error, the file was not received";
}
}
}
Client
class Client
{
public static string ipsendf;//added
public static string MsgCurrent = "Idle";
public static void SendFile(string fName)
{
try
{
IPAddress ip = IPAddress.Parse(ipsendf); //127.0.0.1 in "" as string
IPEndPoint end = new IPEndPoint(ip, 5656);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
string path = "";
fName = fName.Replace("\\", "/");
while (fName.IndexOf("/") > -1)
{
path += fName.Substring(0, fName.IndexOf("/") + 1);
fName = fName.Substring(fName.IndexOf("/") + 1);
}
byte[] fNameByte = Encoding.ASCII.GetBytes(fName);
if (fNameByte.Length > 10 * 1024 * 1024) //count per byte
{
//MsgCurrent = "File is greater than 850 kb";
MsgCurrent = "File is greater than 10MB";
return;
}
MsgCurrent = "Buffering...";
byte[] fileData = File.ReadAllBytes(path + fName);
byte[] clientData = new byte[4 + fNameByte.Length + fileData.Length];
byte[] fNameLen = BitConverter.GetBytes(fNameByte.Length);
fNameLen.CopyTo(clientData, 0);
fNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fNameByte.Length);
MsgCurrent = "Connecting to server ...";
sock.Connect(end);
MsgCurrent = "File sending ...";
sock.Send(clientData);
MsgCurrent = "Disconnecting...";
sock.Close();
MsgCurrent = "The file was sent ..";
}
catch (Exception ex)
{
//do nothing
}
}
}
The default receive size for a socket is 8,192 bytes (for reference). So from your code it looks like on the server, you're only reading the first 8,192 bytes of the message.
You can either increase that buffer size to match the size of the 10MB clientData buffer you allocate, for example, some where after .Accept() and before Receive()..
clientSock.ReceiveBufferSize = 1024 * 1024 * 10;
Or, receive in chunks by checking if there's anything left to read and keep filling up your local buffer. You'll probably get away with the potenitally massive message on a local network though, generally speaking in chunks would be the normal way to do it.
Also, you're using FileMode.Append in the write of the file in server, whereas I would have thought you want FileMode.Create. Otherwise, if you send the same file twice you'll get a 20MB file instead of a 10MB one.
Can anyone give me a small tutorial on how to send file from java server to c# client and on receive complete acknowledgment message from c# to java. Actually I'm new to C# and dont know how to do socket programming. I'm stuck in it since long. Tried many codes. Some codes receive incomplete files some stuck in infinite loop. Please help me in this regard.
Thanks
EDIT
Here is what I have tried:
C# Server:
{
IPAddress ipAd = IPAddress.Parse("192.168.1.131");
// use local m/c IP address, and
// use the same in the client
/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, 5600);
/* Start Listeneting at the specified port */
myList.Start();
Console.WriteLine("The server is running at port 5600...");
Console.WriteLine("The local End point is :" +
myList.LocalEndpoint);
Console.WriteLine("Waiting for a connection.....");
m:
clientSock = myList.AcceptSocket();
//clientSock.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReceiveTimeout,10000);
Console.WriteLine("Connection accepted from " + clientSock.RemoteEndPoint);
//byte[] b = new byte[100];
//int k = clientSock.Receive(b);
string fileName = "hello.wav";
NetworkStream networkStream = new NetworkStream(clientSock);
StreamReader sr = new StreamReader(networkStream);
//read file length
int length = int.Parse(sr.ReadLine());
if (networkStream.CanRead)
{
BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath + fileName, FileMode.Create));
int receivedBytesLen = -1;
byte[] clientData = new byte[4096 * 5000];
receivedBytesLen = networkStream.Read(clientData, 0, clientData.Length);
bWrite.Write(clientData, 0, receivedBytesLen);
do
{
receivedBytesLen = networkStream.Read(clientData, 0,clientData .Length);
bWrite.Write(clientData, 0, receivedBytesLen);
} while (receivedBytesLen > 0);
bWrite.Close();
networkStream.Close();
}
Console.WriteLine("Client:{0} connected & File {1} started received.", clientSock.RemoteEndPoint, fileName);
Console.WriteLine("File: {0} received & saved at path: {1}", fileName, receivedPath);
Recognizer_2 recognizeVoice = new Recognizer_2(clientSock);
recognizeVoice.recognize_wav(); // Acknowledgement
Console.WriteLine("\nResult Sent to the Client");
goto m;
}
Java Client:
Socket socket = new Socket("192.168.1.131", 5600);
BufferedReader response_Stream = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
File f = new File(mFileName);
byte[] buffer = new byte[(int) f.length()];
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(buffer, 0, buffer.length);
OutputStream outputStream = socket.getOutputStream();
outputStream.write(buffer);
outputStream.flush();
String final_Result_String = "";
if (response_Stream != null) {
String respose_text = "";
while ((respose_text = response_Stream.readLine()) != null) {
final_Result_String += respose_text;
}
}
Toast.makeText(getApplicationContext(), final_Result_String, 1)
.show();
outputStream.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
There is no dependance between the languages used by the server or the client.
Just the structure of the data is important !
You should search for some tutorials on socket programming with C#.
For example: http://www.codeproject.com/Articles/10649/An-Introduction-to-Socket-Programming-in-NET-using
But the language doesn't matter, understand how the data is formatted when sent on the network.
Edit: you should add a byte or two in the data indicating the length of it. It's not because you dont have data to read once that all the data has been received.
I am calling this PHP code from Android to transfer file from Android to server and its working perfectly fine.
<?php
$target_path = "./";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
But my server application is in .net and I have to write this code in .net
I tried to write .net version code but it does not work and returns 500 internal server error.
public partial class uploadfiles : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
HttpFileCollection uploadFile = Request.Files;
if (uploadFile.Count > 0)
{
HttpPostedFile postedFile = uploadFile[0];
System.IO.Stream inStream = postedFile.InputStream;
byte[] fileData = new byte[postedFile.ContentLength];
inStream.Read(fileData, 0, postedFile.ContentLength);
postedFile.SaveAs(Server.MapPath("Data") + "\\" + postedFile.FileName);
}
}
catch (Exception ex)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("Message : " +ex.Message);
sb.AppendLine("Source : " + ex.Source);
sb.AppendLine("StackTrace : " + ex.StackTrace);
sb.AppendLine("InnerException : " + ex.InnerException);
sb.AppendLine("ToString : " + ex.ToString());
LogInToFile(sb.ToString());
}
}
}
It does not log any exception or even I think it does not reach to its first line. I checked it through Log file. as it does not work. please help.
Android code is below
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String pathToOurFile = "/data/file_to_send.mp3";
String urlServer = "http://192.168.1.1/handle_upload.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
try
{
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = connection.getResponseCode();
serverResponseMessage = connection.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
catch (Exception ex)
{
//Exception handling
}
The default max file size limit in ASP.NET application is 4 MB. You can configure the application to accept bigger size by setting the below in web.config
<system.web>
<httpRuntime maxRequestLength="20480" />
</system.web>
To learn more about configuring the file size limit check out Large file uploads in ASP.NET
Try this:
postedFile.SaveAs(Server.MapPath("~/Data/" + postedFile.FileName ));
where ~/Data/ is the location where you want to save your file.
then + postedFile.FileName your filename.
Best Regards