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

Most efficient way of reading data from a stream(从流中读取数据的最有效方式)
本文介绍了从流中读取数据的最有效方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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

另一种技术可能是:

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:

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

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
}

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to know if a field is numeric in Linq To SQL(如何在 Linq To SQL 中知道字段是否为数字)
Extract sql query from LINQ expressions(从 LINQ 表达式中提取 sql 查询)
LINQ Where in collection clause(LINQ Where in collection 子句)
Orderby() not ordering numbers correctly c#(Orderby() 没有正确排序数字 c#)
Why do I get quot;error: ... must be a reference typequot; in my C# generic method?(为什么我会收到“错误:...必须是引用类型?在我的 C# 泛型方法中?)
Strange LINQ Exception (Index out of bounds)(奇怪的 LINQ 异常(索引越界))