簡體   English   中英

從流中讀取數據的最有效方式

[英]Most efficient way of reading data from a stream

我有一個使用對稱加密加密和解密數據的算法。 無論如何,當我要解密時,我有:

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 的長度:

在此處輸入圖片說明

或者我應該實現我的堆棧類。 我將加密很多信息,因此使此代碼高效將節省大量時間

你可以分塊閱讀:

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
}

由於您無論如何都將所有內容存儲在內存中,因此您只需使用MemoryStreamCopyTo()

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

CopyTo()將需要 .NET 4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM