开发者

Most efficient way of reading data from a stream

开发者 https://www.devze.com 2023-04-07 13:35 出处:网络
I have an algorithm for encrypting and decrypting data using symmetric encryption. anyways when I am about to decrypt, I have:

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

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 (tr开发者_运维问答ue)
   {
                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

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

Most efficient way of reading data from a stream

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


You could read in chunks:

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
}


Since you are storing everything in memory anyway you can just use a MemoryStream and CopyTo():

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

CopyTo() will require .NET 4

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号