想象一下,Byte[] refArchiveData
的大小约为30-100 MB。我想使用NetworkStream stream
对象将其发送到服务器:
TcpClient client = new TcpClient(server, port);
Byte[] refLengthBytes = new Byte[4];
Byte[] refArchiveData = null;
refArchiveData = File.ReadAllBytes("C:/Temp/Python25.zip");
Console.WriteLine("Archive data length is {0}", refArchiveData.Length);
NetworkStream stream = client.GetStream();
refLengthBytes = System.BitConverter.GetBytes(refArchiveData.Length);
stream.Write(refLengthBytes, 0, 4);
stream.Write(refArchiveData, 0, refArchiveData.Length);
stream.Close();
client.Close();
我如何修改我发送档案的代码部分?也许用256-512字节的块分割它?
感谢您的任何建议!
答案 0 :(得分:7)
使用Stream.CopyTo方法。这样您就不必将整个文件加载到数组中(到内存中)。
using (var file = File.OpenRead("<path to file>"))
using (var client = new TcpClient("<server>", <port>))
using (var netStream = client.GetStream())
{
...
file.CopyTo(netStream);
...
}