从流读出的数据的最有效的方式 [英] Most efficient way of reading data from a stream

查看:92
本文介绍了从流读出的数据的最有效的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对加密和使用对称加密解密数据的算法。反正当我即将解密,我有:

I have an algorithm for encrypting and decrypting data using symmetric encryption. anyways when I am about to decrypt, I have:

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



我要读从CS CryptoStream的数据,并将数据转换成字节数组。所以,一种方法可以是:

I have to read data from the cs CryptoStream and place that data into a array of bytes. So one method could be:

  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();



另一种技术可以是:

another technique could be:

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

I cannot know in advance the length of the stream cs:

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

or perhaps I should implement my stack class. I will be encrypting a lot of information therefore making this code efficient will save a lot of time

推荐答案

您可以在成批读:

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
}

这篇关于从流读出的数据的最有效的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆