I coded a file sharing app using FileStream.CopyTo
copying files for me.To add Progress bar facility in it,I found a dozen of links googling and saying to use CopyFileEx
for Progress bar using CallBack method .After a detailed reading of MSDN docs.I found another option WebClient
for the same purpose and confused me rather more.I then skimmed through here where the author doesn't talk about Stream.CopyTo
but advocating CopyFileEx
too.
I am already done with coding using CopyTo
method.For progress bar will it provide me facility and how?
PS. I searched a lot but none of link showed me how to implement it using CopyTo
.
Here's my code For Client-side:
NetworkStream netstream = clientSocket.GetStream();
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
try
{
TransmitFileName(netstream, Path.GetFileName(path));
// MessageBox.Show("Starting Data Transfer");
int data_len = (int)fs.Length;
byte[] buffer = new byte[bufferSize];
int totalbytes = 0;
while (totalbytes < data_len)
{
var bytesread = fs.Read(buffer, 0, buffer.Length);
if (totalbytes == data_len) { break; }
try
{
netstream.Write(buffer, 0, bytesread);
totalbytes += bytesread;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
string suff_tb= SizeSuffix(totalbytes);
MessageBox.Show("Total Bytes Receieved" + suff_tb);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
MessageBox.Show("Data transfer completed");
fs.Close();
netstream.Close();
}
}
Server-side:
Directory.CreateDirectory(Path.GetDirectoryName(fileloc));
//copy data from client machine to local drive
try
{
using (FileStream fs = new FileStream(fileloc, FileMode.OpenOrCreate, FileAccess.Write))
{
netStream.CopyTo(fs);
}
}
catch (Exception exx)
{
MessageBox.Show(exx.ToString());
}
finally
{
netStream.Close();
FileInfo fi = new FileInfo(fileloc);
long siz = fi.Length;
MessageBox.Show("File Size is" + SizeSuffix(siz));
}