从流中读取数据的最有效方法

Ton*_*Nam 25 c# performance stream

我有一个使用对称加密来加密和解密数据的算法.无论如何,当我要解密时,我有:

CryptoStream cs = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Read);
Run Code Online (Sandbox Code Playgroud)

我必须从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();
Run Code Online (Sandbox Code Playgroud)

另一种技术可能是:

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
Run Code Online (Sandbox Code Playgroud)

我事先无法知道流cs的长度:

在此输入图像描述

或者我应该实现我的堆栈类.我将加密大量信息,因此使代码高效将节省大量时间

Dar*_*rov 54

你可以阅读大块的内容:

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
}
Run Code Online (Sandbox Code Playgroud)

  • @Tono Nam,它确保始终调用诸如Streams之类的IDisposable资源的Dispose方法,以便释放它们可能保留的任何非托管资源,即使在异常的情况下也可以避免代码中的内存泄漏.这是我邀请您在MSDN上阅读的基本概念:http://msdn.microsoft.com/en-us/library/yh598w02.aspx此外,您应该将`CryptoStream`包装到using语句中. (2认同)
  • 如果是.NET 4,也应该使用`CopyTo()`;-) (2认同)

Bro*_*ass 31

因为你将所有内容存储在内存中,你只需使用MemoryStreamCopyTo():

using (MemoryStream ms = new MemoryStream())
{
    cs.CopyTo(ms);
    return ms.ToArray();
}
Run Code Online (Sandbox Code Playgroud)

CopyTo() 将需要.NET 4