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

问题描述:

我有一个使用对称加密来加密和解密数据的算法。反正当我即将解密,我有:从流中读取数据的最有效方式

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

也许我应该实现我的堆栈类。我会被加密了大量的信息,因此使这个代码效率将节省大量的时间

你可以在成批读:

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语句。 –

既然你是存储在内存中的一切,反正你可以只使用一个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

不能相信我错过了我的一生 –