经过大量的研究和研究后,我建议在Stackoverflow上更好地使用FileStream
在客户端计算机上打开文件,在将数据发送到服务器之前发送文件名(在预定义的端口侦听) ,读取缓冲区块中的固定大小的数据,将其发送到远程服务器。所有这些操作都由我使用各种缓冲区大小进行测试,现在从10kb到100MB开始。我测试了它的小文件和它工作得很好。我带着发送2GB文件的有用想法。花了将近一个小时。
以下是简短的编码理念。
客户端:
try
{
clientSocket.Connect(new IPEndPoint(ipaddrcl, port));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
NetworkStream netstream = clientSocket.GetStream();
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
try
{
TransmitFileName(netstream, Path.GetFileName(path));
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);
pictureBox.Image = Properties.Resources.Warning;
labelProgress.Text = "Error in transmission";
}
}
}
finally
{
MessageBox.Show("Data transfer completed");
pictureBox.Image = Properties.Resources.Information;
labelProgress.Text = "Copying Done";
fs.Close();
netstream.Close();
// change button states
btnSend.Enabled = true;
btn_Cancel.Enabled = false;
}
}
服务器端:
Directory.CreateDirectory(Path.GetDirectoryName(fileloc));
try
{
using (FileStream fs = new FileStream(fileloc, FileMode.OpenOrCreate, FileAccess.Write))
{
netStream.CopyTo(fs);
pictureBox2.Image = Properties.Resources.spinningDisc1;
// label_server.Text = "Receiving Data";
}
}
catch (Exception e)
{
MessageBox.Show(e.Message.ToString());
}
finally
{
//check the size of file recieved
FileInfo fi = new FileInfo(fileloc);
long siz = fi.Length;
MessageBox.Show("Data Recieved: File Size is " + SizeSuffix(siz));
pictureBox2.Image = null;
// Thread();
}
为了提高速度,我遇到了here并测试了CopyFileEx
来复制本地主机上的文件夹和树,并且它工作得非常好。
现在的问题是,我可以在WLAN上使用CopyFileEx
吗?是的,是的,这将如何确保我编写一个块大块的数据并仍然确保快速处理。