I am very new to Java and C#. I have a java app that is sending the filename and file to a C# client using TCP Socket. I receive the data but it is corrupt when writing. I do not know how to first read the file name and then rest of the data to write the file.
I have written code that if I just send the file from my java app I successfully receive it on my C# app and write it successfully. This works 100%. Now I want to send the name and file.
Java code sending the data:
try {
System.out.println("Connecting...");
File file = new File(Environment.getExternalStorageDirectory(), backup_folder);
File[] Files = file.listFiles();
OutputStream os = m_socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeInt(Files.length);
for (int count = 0; count < Files.length; count++) {
dos.writeUTF(Files[count].getName());
}
for (int count = 0; count < Files.length; count++) {
int filesize = (int) Files[count].length();
dos.writeInt(filesize);
}
for (int count = 0; count < Files.length; count++) {
int filesize = (int) Files[count].length();
byte[] buffer = new byte[filesize];
FileInputStream fis = new FileInputStream(Files[count].toString());
BufferedInputStream bis = new BufferedInputStream(fis);
//Sending file name and file size to the server
bis.read(buffer, 0, buffer.length); //This line is important
dos.write(buffer, 0, buffer.length);
dos.flush();
//close socket connection
//socket.close();
}
m_socket.close();
} catch (Exception e) {
System.out.println("Error::" + e);
//System.out.println(e.getMessage());
//e.printStackTrace();
//Log.i("******* :( ", "UnknownHostException");
}
}
C# code (this is where I am having my problem)
private void WaitConnection()
{
toolStripStatusLabel2.Visible = true;
toolStripStatusLabel1.Visible = false;
while (true){
m_listener.Start();
m_client = m_listener.AcceptTcpClient();
if (m_client.Connected == true)
{
this.Invoke((MethodInvoker)delegate
{
this.toolStripStatusLabel4.Visible = false;
this.toolStripStatusLabel5.Visible = false;
this.toolStripStatusLabel3.Visible = true;
});
}
using (var stream = m_client.GetStream())
using (var output = File.Create("C:\\Stocktake\\EDADatabase.db"))
{
byte[] buffer;
buffer = new byte[1024];
int bytesRead = -1;
progressBar1.BeginInvoke(new MethodInvoker(delegate { progressBar1.Maximum = 50; })); //Set Progessbar maximum
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
var xml = Encoding.UTF8.GetString(buffer,0,bytesRead);
string rec = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead);
output.Write(buffer, 0, bytesRead);
progressBar1.Invoke(new updatebar(this.UpdateProgress));
}
if (bytesRead == 0)
{
Completed = true;
this.Invoke((MethodInvoker)delegate
{
this.m_client.GetStream().Close();
this.m_client.Dispose();
this.m_listener.Stop();
this.toolStripStatusLabel3.Visible = false;
this.toolStripStatusLabel5.Visible = true;
});
progressBar1.Invoke(new updatebar(this.UpdateProgress));
//break;
}
}
}
}
All I want to do is read the file name and use the file name to read and save the data to my pc.
Related
So I am trying to download file with FTP and want to show current progress on a progress bar component. I run task like this with custom FtpClient class:
SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == true)
{
pBar.Visibility = Visibility.Visible;
string status = "";
string filename = entry.FileName.Text;
await Task.Run(() =>
{
status = client.DownloadFile(filename, sfd.FileName, pBar);
});
statusBox.Text = status.Substring(4);
}
public string DownloadFile(string source, string dest, ProgressBar pBar)
{
FtpWebRequest sizeRequest = CreateRequest(CombinePaths(url, source), WebRequestMethods.Ftp.GetFileSize); // creates FtpWebRequest and assigns method
FtpWebResponse sizeResponse = (FtpWebResponse)sizeRequest.GetResponse();
if (sizeResponse.ContentLength <= 0) // if server does not support SIZE
pBar.IsIndeterminate = true;
else
{
pBar.IsIndeterminate = false; // fails here since progress bar is in the another thread
pBar.Maximum = sizeResponse.ContentLength;
pBar.Value = 0;
}
byte[] buffer = new byte[buffSize];
using (FtpWebResponse dlResponse = (FtpWebResponse)dlRequest.GetResponse())
{
using (Stream stream = dlResponse.GetResponseStream())
{
using (FileStream fs = new FileStream(dest, FileMode.OpenOrCreate))
{
int readCount = stream.Read(buffer, 0, buffSize);
while (readCount > 0)
{
fs.Write(buffer, 0, readCount);
pBar.Value = pBar.Value + readCount;
readCount = stream.Read(buffer, 0, buffSize);
}
}
}
return dlResponse.StatusDescription;
}
Is there a way to make this work? Since I am downloading and trying to update UI I don't know is there is a way to do what I want
pBar.Dispatcher.Invoke(() =>
{
if (GetFileSize(source) <= 0)
pBar.IsIndeterminate = true;
else
{
pBar.IsIndeterminate = false;
pBar.Maximum = GetFileSize(source);
pBar.Value = 0;
}
});
// code...
pBar.Dispatcher.Invoke(() =>
{
pBar.Value = pBar.Value + readCount;
});
Used dispatcher to update progress bar, works flawlessly
I convert image file into a byte array and packetize it to 14-byte packets and send it via SerialPortEventHandler. on the other hand, in reciever part I lost some packets and when I generate recieved byte array in a new image file, the rest of the image, after the lost packet, shifted incorrectly, I have replaced lost packets with zero. while this works with text file perfectly. This is my code in client and server side:
client
_file = ofile.ConvertFileToByte(txtFileName.Text);
for (int k = 0; k < Configuration.PacketNumberInFrame; k++)
{
((BackgroundWorker)sender).ReportProgress((j * Configuration.PacketNumberInFrame + i) * 100 / Configuration.FileCount);
if (i + _numberOfByte <= Configuration.FileCount)
_packet = _file.SubArray(i, _numberOfByte);
}
//send packet
...
Server
try
{
while (true)
{
size = port.BytesToRead;
if (size >= 18)
break;
}
byte[] packet = new byte[size];
var str2 = port.Read(packet, 0, size);
if (System.Text.Encoding.Default.GetString(packet).Contains(Configuration.EndKeyByte) && !endFlag)
EndRecieving();
else
Extract(packet);
}
catch
(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public Extract(packet)
{
Recieve_Data.Add( packet);
}
public EndRecieving()
{
for(int i=0;i< arrayResult.AddRange(packetData);i++)
{
arrayResult.AddRange(packetData);
}
string filePath = Configuration.LogFilePath + "\\CreatedFile-" + "."filePrefix.ToLower();
var stream = new FileStream(filePath,
FileMode.Create,
FileAccess.ReadWrite);
FileData oFile = new FileData();
stream.Write(result, 0, result.Length);
stream.Close();
}
I have tried every solution I could find but nothing seems to work. Anything other than text files becomes corrupted; someone said that TCP can't send more than 8KB, so I tried to fix the problem and I think I did. Now, when I send a text file (no matter what size it is), it reaches perfectly but anything else gets corrupted. I know the code for the cutting is expensive to performance but I am going to think about that later.
Here is my sender code:
private string SendFile(string tosend, string tosendname)
{
ipadd = IPAddress.Parse(textBox2.Text);
ep = new IPEndPoint(ipadd, 6112);
Sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
Sender.Connect(ep);
Thread.Sleep(100);
byte[] filetosend = System.IO.File.ReadAllBytes(tosend);
FileStream fs = new FileStream(tosend, FileMode.Open, FileAccess.Read);
//Read byte from image
fs.Read(filetosend, 0, filetosend.Length);
fs.Flush();
fs.Close();
int countt = filetosend.Count();
int dividedcount = countt / 7000;
Sender.Send(Encoding.ASCII.GetBytes("filesize#" + filetosend.Count().ToString()));
Thread.Sleep(500);
List<byte> cuttedtosend = new List<byte>();
for (int counti = 0; counti < dividedcount; counti++)
{
cuttedtosend = new List<byte>();
for (int index = 0; index < 7000; index++)
{
cuttedtosend.Add(filetosend[(filetosend.Count() - countt) + index]);
}
Sender.Send(cuttedtosend.ToArray());
Thread.Sleep(100);
countt -= 7000;
richTextBox1.Invoke((MethodInvoker)delegate { richTextBox1.AppendText("Countt = " + countt + "\n"); });
richTextBox1.Invoke((MethodInvoker)delegate { richTextBox1.AppendText("Counti = " + counti + "\n"); });
}
richTextBox1.Invoke((MethodInvoker)delegate { richTextBox1.AppendText("Done"); });
cuttedtosend = new List<byte>();
for (int index = filetosend.Count() - countt; index < filetosend.Count(); index++)
{
//richTextBox1.Invoke((MethodInvoker)delegate { richTextBox1.AppendText(index + "this is 2 \n"); });
cuttedtosend.Add(filetosend[index]);
}
Sender.Send(cuttedtosend.ToArray());
countt -= countt;
return "";
}
And here is my receive code:
private async void StartReceiving()
{
List<byte> neededbytes = new List<byte>();
receivedbyte = new byte[InputForm.s];
Receiver.Bind(new IPEndPoint(IPAddress.Parse("0"), 6112));
Receiver.Listen(1000);
string filename = "Downloadedfile";
bool cont = false;
while (true)
{
Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
Client = Receiver.Accept();
int filesize = 0;
byte[] receivechecker = new byte[100];
Client.Receive(receivechecker);
if(Encoding.ASCII.GetString(receivechecker).Contains("filesize#"))
{
filesize = Convert.ToInt32(Encoding.ASCII.GetString(receivechecker).Remove(0, 9));
Client.Receive(receivechecker);
}
if (Encoding.ASCII.GetString(receivechecker).Contains("#100254#"))
{
string[] splttedtext = Encoding.ASCII.GetString(receivechecker.ToArray()).Split('#');
if (splttedtext[0] == "mess")
{
MessageBox.Show(splttedtext[2]);
}
else if (splttedtext[0] == "filename")
{
//MessageBox.Show(splttedtext[2]);
filename = splttedtext[2];
//filename.Replace(#"\", #"/");
cont = true;
}
}
else
{
List<byte> tosave = new List<byte>();
richTextBox1.Invoke((MethodInvoker)delegate { richTextBox1.AppendText(filesize.ToString() + "\n"); });
int countt = filesize / 7000;
FileStream writer = File.Create("DownloadedFile.jpg");
for (int counti = 0; counti < countt; counti++)
{
byte[] toadd = new byte[7000];
richTextBox1.Invoke((MethodInvoker)delegate { richTextBox1.AppendText("Counti = " + counti.ToString() + "\n"); });
Client.Receive(toadd);
writer.Write(toadd,0,toadd.Count());
neededbytes.AddRange(toadd);
filesize -= 7000;
}
richTextBox1.Invoke((MethodInvoker)delegate { richTextBox1.AppendText(filesize.ToString() + "\n"); });
byte[] toadds = new byte[filesize];
Client.Receive(toadds);
writer.Write(toadds,0,toadds.Count());
writer.Close();
neededbytes.AddRange(toadds);
filesize -= filesize;
}
}
Thanks in advance :D
Edit:
I just tried Sending a 7mb text file and it reached complete.......
The most immediate problem is that you're saving bytes that you didn't necessarily receive. For example, you have:
for (int counti = 0; counti < countt; counti++)
{
byte[] toadd = new byte[7000];
richTextBox1.Invoke((MethodInvoker)delegate { richTextBox1.AppendText("Counti = " + counti.ToString() + "\n"); });
Client.Receive(toadd);
writer.Write(toadd,0,toadd.Count());
neededbytes.AddRange(toadd);
filesize -= 7000;
}
The documentation for Receive says that the method will receive up to the number of bytes you request. It's not uncommon for it to return fewer bytes than you requested, especially at the end of the file (since it couldn't receive more than the file length).
You need to write:
var bytesRead = Client.Receive(toadd);
writer.Write(toadd, 0, bytesRead); // only write as many bytes as you've read
In general, your code is pretty convoluted, and you have several other possible problems just waiting to bite you. For example, the code that sends the file size sleeps for 500 ms, which just happens to be enough time for the receiver to read just the number of bytes sent. Without that sleep, your code would fail.
You have code to receive the file name, but no code to send it.
I would suggest that you eliminate the ASCII tags and send things in binary. Below is your rewritten Send method.
private string SendFile(string tosend, string tosendname)
{
ipadd = IPAddress.Parse(textBox2.Text);
ep = new IPEndPoint(ipadd, 6112);
Sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
Sender.Connect(ep);
byte[] filetosend = System.IO.File.ReadAllBytes(tosend);
byte[] filesizeBytes = BitConverter.GetBytes(filetosend.Length);
Sender.Send(filesizeBytes); // sends the length as an integer
// note: You could use Socket.Send(filetosend) here.
// but I'll show an example of sending in chunks.
int totalBytesSent = 0;
while (totalBytesSent < filetosend.Length)
{
int bytesLeft = filetosend.Length - totalBytesSent;
int bytesToSend = Math.Min(bytesLeft, 7000);
Sender.Send(filetosend, totalBytesSent, bytesToSend);
richTextBox1.Invoke((MethodInvoker)delegate
{ richTextBox1.Append(totalBytesSent + " bytes sent\n"); });
totalBytesSent += bytesToSend;
}
richTextBox1.Invoke((MethodInvoker)delegate { richTextBox1.AppendText("Done"); });
return "";
}
The receiver code is similarly simplified:
private async void StartReceiving()
{
Receiver.Bind(new IPEndPoint(IPAddress.Parse("0"), 6112));
Receiver.Listen(1000);
string filename = "Downloadedfile";
bool cont = false;
while (true)
{
Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
Client = Receiver.Accept();
// read the length
byte[] filesizeBytes = new byte[4];
int totalBytesReceived = 0;
while (totalBytesReceived < 4)
{
int bytesRead = Client.Receive(
filesizeBytes, totalBytesReceived, 4-totalBytesReceived);
totalBytesReceived += bytesRead;
}
int filesize = BitConverter.ToInt32(filesizeBytes);
richTextBox1.Invoke((MethodInvoker)delegate
{ richTextBox1.AppendText(filesize.ToString() + "\n"); });
// now read the file
using (FileStream writer = File.Create("DownloadedFile.jpg"))
{
byte[] readBuffer = new byte[7000];
totalBytesReceived = 0;
while (totalBytesReceived < filesize)
{
int bytesToRead = Math.Min(7000, filesize - totalBytesReceived);
int bytesRead = Client.Receive(readBuffer, 0, bytesToRead);
totalBytesRead += bytesRead;
writer.Write(readBuffer, 0, bytesRead);
richTextBox1.Invoke((MethodInvoker)delegate
{ richTextBox1.AppendText("Read " + bytesRead.ToString() + "bytes\n"); });
}
richTextBox1.Invoke((MethodInvoker)delegate
{ richTextBox1.AppendText("Done. " + totalBytesRead.ToString() + " bytes\n"); });
}
}
If you want to send the file name, then I would suggest converting it to UTF8 (Encoding.UTF8.GetBytes(filename)), then send an int (4 bytes) that says how long it is, and then the buffer. To receive it, read the 4-byte filename length like I showed how to read the file size, then that many bytes for the file name, and convert back to a string (Encoding.UTF8.GetString(bytes, 0, filenameLength)).
Please excuse any typos or minor errors in the code. I'm doing this from memory and trying to keep somewhat with your coding style.
i suspect that you are expecting the same blocks that you send to be received; ie that record boundaries will be preserved. This is not so. TCP guarantees that every byte sent will be received and that order is preserved; but you could do 1 large 10k send and receive 10k 1 byte messages.
I am trying to develop an app that will upload large files to a web server running PHP. Almost immediately, I stumbled upon a problem that the file is not split correctly.
Currently I have this piece of code
string adrese = "c:\\directory\\file.jpg";
int garums = 16384;
String ext = Path.GetExtension(adrese);
FileStream file = /*/File.Open(adrese, FileMode.Open);/*/
new FileStream(adrese, FileMode.Open, System.IO.FileAccess.Read);
long fgar = file.Length; //100%
long counter = garums;
first = true;
byte[] chunk = new byte[garums];
while (true)
{
int index = 0;
//long Controll = counter+garums;
while (index < chunk.Length)
{
int bytesRead = file.Read(chunk, index, chunk.Length - index);
if (bytesRead == 0)
{
/*byte[] biti = new byte[index];
for (int i = 0; i < index; i++)
{
biti[i] = chunk[i];
}
chunk = new byte[index];
chunk = biti;*/
break;
}
index += bytesRead;
}
if (index != 0) // Our previous chunk may have been the last one
{
byte[] biti = new byte[index];
for (int i = 0; i < index; i++)
{
biti[i] = chunk[i];
}
chunk = new byte[index];
chunk = biti;
// index is the number of bytes in the chunk
sutam(Convert.ToBase64String(chunk),ext);
}
double procentuali = ((counter * 100) / fgar);
if (procentuali > 99)
{
procentuali = 100;
}
progressBar1.Value = (int)Math.Round(procentuali);
label1.Text = "" + procentuali;
counter = counter+garums;
if (index != garums) // We didn't read a full chunk: we're done
{
return;
}
}
file.Close();
Everything works if I set garums to 1, but who will wait for a year or so to upload a file sized multiple GB's.
I would be pleased if you could tell me what is wrong and how to fix this.
Try this instead to upload in chunks:
private void ConvertToChunks()
{
//Open file
string file = MapPath("~/temp/1.xps");
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
//Chunk size that will be sent to Server
int chunkSize = 1024;
// Unique file name
string fileName = Guid.NewGuid() + Path.GetExtension(file);
int totalChunks = (int)Math.Ceiling((double)fileStream.Length / chunkSize);
// Loop through the whole stream and send it chunk by chunk;
for (int i = 0; i < totalChunks; i++)
{
int startIndex = i * chunkSize;
int endIndex = (int)(startIndex + chunkSize > fileStream.Length ? fileStream.Length : startIndex + chunkSize);
int length = endIndex - startIndex;
byte[] bytes = new byte[length];
fileStream.Read(bytes, 0, bytes.Length);
ChunkRequest(fileName, bytes);
}
}
private void ChunkRequest(string fileName,byte[] buffer)
{
//Request url, Method=post Length and data.
string requestURL = "http://localhost:63654/hello.ashx";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// Chunk(buffer) is converted to Base64 string that will be convert to Bytes on the handler.
string requestParameters = #"fileName=" + fileName + "&data=" + HttpUtility.UrlEncode( Convert.ToBase64String(buffer) );
// finally whole request will be converted to bytes that will be transferred to HttpHandler
byte[] byteData = Encoding.UTF8.GetBytes(requestParameters);
request.ContentLength = byteData.Length;
Stream writer = request.GetRequestStream();
writer.Write(byteData, 0, byteData.Length);
writer.Close();
// here we will receive the response from HttpHandler
StreamReader stIn = new StreamReader(request.GetResponse().GetResponseStream());
string strResponse = stIn.ReadToEnd();
stIn.Close();
}
I have a Network File Transfer here. It works fine and great. But I just had a problem on how to lessen my CPU usage to 5% in transferring small files like 200kb and below.
All the large file I transfer just had a 0 - 2% of CPU usage. But when I tried to transfer a small file it bursts to 7% to 20%. How could that be?
Any suggestions?
Here's my code...
For my Client:
private void SendFiles(){
try
{
FileInfo file;
//Checks first if it is connected
if (tcpClient.Connected == false)
{
//Create new instance
tcpClient = new TcpClient();
// Connect the TCP client to the specified IP and port
tcpClient.Connect(txtIP.Text, Convert.ToInt32(txtPort.Text));
}
// Get a stream connected to the server
streamSend = tcpClient.GetStream();
// byte[] byteSend = new byte[tcpClient.ReceiveBufferSize];
byte[] byteSend = new byte[byteLength];
int listCount = arrList.Count - indxItems;
byteSend = System.Text.Encoding.ASCII.GetBytes(listCount.ToString().PadRight(byteLength).ToCharArray());
// Write the sequence of bytes (the count of the items in the listbox) to the network stream
streamSend.Write(byteSend, 0, byteSend.Length);
while (indxItems < arrList.Count)
{
fName = arrList[indxItems].ToString();
// grab file info
file = new System.IO.FileInfo(fName);
SendFile(fName, streamSend, byteSend);
Thread.Sleep(1000);
minimizeMemory();
indxItems++;
}
if (indxItems == arrList.Count)
if (MessageBox.Show("Done Sending!\r\nClearing list of sent file(s) and/or folder(s)", "Done Sending", MessageBoxButtons.OK) == DialogResult.OK)
{
this.Invoke(new Clear(this.ClearList), new object[] { true });
tcpClient.Close();
streamSend.Close();
readFile.Close();
}
}
catch (SocketException exMessage)
{
MessageBox.Show("Can't send, Server not available.\r\nSearch for another connection.", "Sending Error!");
this.Invoke(new Clear(this.ClearList), new object[] { true });
}
}
For my SendFile Method:
private void SendFile(String fName, NetworkStream netStream, byte[] byteSend)
{
minimizeMemory();
try
{
readFile = new FileStream(fName, FileMode.Open, FileAccess.Read);
// Get file info about the opened file
FileInfo fileInfo = new FileInfo(fName);
// Get and store the file size
long FileSize = Convert.ToInt64(fileInfo.Length);
// Get and store the file name
String FileName = fileInfo.Name;
byteSend = System.Text.Encoding.ASCII.GetBytes(FileName.PadRight(byteLength).ToCharArray());
// Write the sequence of bytes (file name) to the network stream
netStream.Write(byteSend, 0, byteSend.Length);
byteSend = System.Text.Encoding.ASCII.GetBytes(FileSize.ToString().PadRight(byteLength).ToCharArray());
// Write the sequence of bytes (file size) to the network stream
netStream.Write(byteSend, 0, byteSend.Length);
Thread.Sleep(50);
int byteRead = 0;
// Define the buffer size
byte[] downBuffer = new byte[byteLength];
// Loop through the file strem of the local file
while (((byteRead = readFile.Read(downBuffer, 0, downBuffer.Length)) > 0) && (streamSend != null))
{
// Write the data that composes the file to the network stream
netStream.Write(downBuffer, 0, byteRead);
uploadSize += byteRead;
Thread.Sleep(200);
}
minimizeMemory();
}
catch (SocketException se)
{
MessageBox.Show("Can't connect, Server not available.", "Connection Error!");
this.Invoke(new Clear(this.ClearList), new object[] { true });
}
catch (InvalidOperationException ioe)
{
MessageBox.Show("Action might be closed by the Server.", "Connection Error!");
this.Invoke(new Clear(this.ClearList), new object[] { true });
}
catch (IOException ioe)
{
MessageBox.Show("Action might be closed by the Server.", "Connection Error!");
this.Invoke(new Clear(this.ClearList), new object[] { true });
}
}
And here's for my Server:
private void DownloadFromConnection(TcpClient tcpConn, String ipadd)
{
try
{
bool disconnected = false;
fCount = 0;
success = 0;
byteLength = 1024 * 100;
// For holding the number of bytes we are reading at one time from the stream
int bytesSize = 0;
// String to hold the FilePath
String filePath = String.Empty;
// The buffer that holds the data received from the client
byte[] downloadBuffer = new byte[byteLength];
// Receive the stream and store it in a NetworkStream object
strRemote = tcpConn.GetStream();
// Read the first buffer(byteLength bytes) from the stream - which represents the count of file(s)/folder(s) to be received.
bytesSize = strRemote.Read(downloadBuffer, 0, byteLength);
fCount = Convert.ToInt32(System.Text.Encoding.ASCII.GetString(downloadBuffer, 0, bytesSize).Trim());
if (fCount > 0)
{
for (int i = fCount; i > 0; i--)
{
disconnected = DownloadFilesFromConnection(bytesSize, ipadd, filePath, downloadBuffer);
if (disconnected)
break;
Thread.Sleep(50);
minimizeMemory();
}
if (success == fCount)
{
MessageBox.Show(fCount + " file(s) from " + ipadd + " successfully received.", "File Received");
}
}
isReceiving = false;
}
catch
{
this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { false, 0 });
}
finally
{
// This part of the method will fire no matter wether an error occured in the above code or not
if (strLocal != null && strRemote != null)
{
// Close the streams
strLocal.Close();
strRemote.Close();
}
}
}
For DownloadFilesFromConnection Method:
private bool DownloadFilesFromConnection(int byteSize, String ipAddress, String filepath, byte[] downloadBuffer)
{
minimizeMemory();
// Cancels receiving operations if client is disconnected
bool clientDisconnected = false;
try
{
// The buffer that holds the data received from the client
downloadBuffer = new byte[byteLength];
this.Invoke(new IsCurrReceivingF(this.IsCurrRecF), new object[] { true });
// Read the buffer (byteLength bytes) from the stream - which represents the file name
byteSize = strRemote.Read(downloadBuffer, 0, byteLength);
// Convert the stream to string and store the file name
FName = System.Text.Encoding.ASCII.GetString(downloadBuffer, 0, byteSize).Trim();
// String to hold the FilePath
filepath = destPath + "\\" + FName;
this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { true, 1 });
// Set the file stream to the path C:\ plus the name of the file that was on the sender's computer
strLocal = new FileStream(filepath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
// Read the next buffer (byteLength bytes) from the stream - which represents the file size
byteSize = strRemote.Read(downloadBuffer, 0, byteLength);
// Convert the file size from bytes to string and then to long (Int64)
long FileSize = Convert.ToInt64(System.Text.Encoding.ASCII.GetString(downloadBuffer, 0, byteSize).Trim());
long size = 0;
int update = 0;
// From now on we read everything that's in the stream's buffer because the file content has started
while ((byteSize = strRemote.Read(downloadBuffer, 0, downloadBuffer.Length)) >= 0 && size != FileSize)
{
if (byteSize == 0 && size != FileSize)
{
ForceStopDownload(strLocal, strRemote, ipAddress);
this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { false, 1 });
if (File.Exists(filepath))
{
File.Delete(filepath);
this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { false, 1 });
this.Invoke(new UpdateProgressCallback(this.UpdateProgress), new object[] { 0, 0 });
this.Invoke(new UpdateProgressFileCallback(this.UpdateProgressFile), new object[] { 0, 0 });
FName = String.Empty;
}
MessageBox.Show("Only " + success + " file(s) successfully copied from " + ipAddress + ".", "File Transferring Canceled");
clientDisconnected = true;
break;
}
else
{
update++;
// Write the data to the local file stream
strLocal.Write(downloadBuffer, 0, byteSize);
size += byteSize;
downloadedSize += byteSize;
if (update == 2)
{
// Update the progressbar by passing the file size and how much we downloaded so far to UpdateProgress()
this.Invoke(new UpdateProgressCallback(this.UpdateProgress), new object[] { strLocal.Length, FileSize });
this.Invoke(new UpdateProgressFileCallback(this.UpdateProgressFile), new object[] { strLocal.Length, FileSize });
update = 0;
}
if (size == FileSize)
{
// Write the status to the log textbox on the form (txtLog)
this.Invoke(new UpdateProgressCallback(this.UpdateProgress), new object[] { 0, 0 });
this.Invoke(new UpdateProgressFileCallback(this.UpdateProgressFile), new object[] { 0, 0 });
FName = String.Empty;
success++;
break;
}
}
Thread.Sleep(1);
}
if (clientDisconnected)
return clientDisconnected;
}
catch (ObjectDisposedException ode)
{
;
}
catch (InvalidOperationException ioe)
{
;
}
return clientDisconnected;
}
I know my codes are not that good. I'm new in C# but hoping to have answers to my questions.=)