2011-09-24 52 views
16

我有一個使用對稱加密來加密和解密數據的算法。反正當我即將解密,我有:從流中讀取數據的最有效方式

CryptoStream cs = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Read); 

我要讀從CS CryptoStream的數據和數據放入字節數組。所以一個方法可以是:

System.Collections.Generic.List<byte> myListOfBytes = new System.Collections.Generic.List<byte>(); 

    while (true) 
    { 
       int nextByte = cs.ReadByte(); 
       if (nextByte == -1) break; 
       myListOfBytes.Add((Byte)nextByte); 
    } 
    return myListOfBytes.ToArray(); 

另一種技術可能是:

ArrayList chuncks = new ArrayList(); 

byte[] tempContainer = new byte[1048576]; 

int tempBytes = 0; 
while (tempBytes < 1048576) 
{ 
    tempBytes = cs.Read(tempContainer, 0, tempContainer.Length); 
    //tempBytes is the number of bytes read from cs stream. those bytes are placed 
    // on the tempContainer array 

    chuncks.Add(tempContainer); 

} 

// later do a for each loop on chunks and add those bytes 

我不能預先知道流的長度CS:

enter image description here

也許我應該實現我的堆棧類。我會被加密了大量的信息,因此使這個代碼效率將節省大量的時間

回答

42

你可以在成批讀:

using (var stream = new MemoryStream()) 
{ 
    byte[] buffer = new byte[2048]; // read in chunks of 2KB 
    int bytesRead; 
    while((bytesRead = cs.Read(buffer, 0, buffer.Length)) > 0) 
    { 
     stream.Write(buffer, 0, bytesRead); 
    } 
    byte[] result = stream.ToArray(); 
    // TODO: do something with the result 
} 
+0

漂亮感謝那正是我需要的! –

+0

快速問題...爲什麼你把所有內容放在使用陳述中?使用說明是什麼意思? –

+2

@Tono Nam,它確保始終調用諸如Stream之類的IDisposable資源的Dispose方法,以便釋放它們可能持有的任何非託管資源,即使發生異常也可以避免代碼中的內存泄漏。這是一個基本概念,我邀請你在MSDN上閱讀:http://msdn.microsoft.com/en-us/library/yh598w02.aspx此外,你應該將'CryptoStream'包裝成using語句。 –

25

既然你是存儲在內存中的一切,反正你可以只使用一個MemoryStreamCopyTo()

using (MemoryStream ms = new MemoryStream()) 
{ 
    cs.CopyTo(ms); 
    return ms.ToArray(); 
} 

CopyTo()需要.NET 4

+0

CryptoStream類不包含copyTo方法... –

+0

@TonoNam:在.NET 4中'CopyTo()'在'Stream'上定義 - 如果您的解決方案針對早期版本的.NET,則所有流支持它。 @達林斯解決方案 – BrokenGlass

+0

不能相信我錯過了我的一生 –

相關問題