Most efficient way of reading data from a stream

后端 未结 2 1583
闹比i
闹比i 2020-12-01 10:29

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

CryptoStream cs = new CryptoSt         


        
相关标签:
2条回答
  • 2020-12-01 11:09

    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
    }
    
    0 讨论(0)
  • 2020-12-01 11:23

    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 讨论(0)
提交回复
热议问题