2010-12-13 114 views
4

想象一下,Byte[] refArchiveData大小約爲30-100兆字節。我想用NetworkStream stream對象將其發送到服務器:C#套接字重構(數據發送)

  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字節塊?

謝謝你的任何建議!

回答

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); 
    ... 
} 
+0

謝謝!我會嘗試;) – Edward83 2010-12-13 11:46:00

+0

你的解決方案的工作完美!;) – Edward83 2010-12-13 12:16:11

+2

好吧,我認爲這是一個框架功能,而不是我的解決方案... – m0sa 2010-12-13 12:20:09