简体   繁体   English

memorystream(byte [])vs memorystream.write(byte [])

[英]memorystream(byte[]) vs memorystream.write(byte[])

I needed to put a byte to a memory stream so initially, I used: 我需要在内存流中放入一个字节,因此最初使用:

byte[] Input;
using (MemoryStream mem = new MemoryStream())
{
    mem.Write(Input, 0, (int)Input.Length);
    StreamReader stream = new StreamReader(mem);
    ...
}

I wanted to use the Streamreader to read lines from a text file. 我想使用Streamreader从文本文件读取行。

It didn't work. 没用

Then I used 然后我用

using (MemoryStream mem = new MemoryStream(Input))

instead and removed 而是删除

mem.Write(Input, 0, (int)Input.Length);

It worked. 有效。 I don't know why. 我不知道为什么 Why did it work? 为什么起作用?

In your first approach, you use mem.Write(Input, 0, (int)Input.Length); 第一种方法是使用mem.Write(Input, 0, (int)Input.Length); . Note that MemoryStream.Write sets the stream read/write position behind the written data. 请注意, MemoryStream.Write设置流在已写入数据之后的读/写位置。 In your example case this is equivalent with a position signifying the end of the stream. 在您的示例中,这等同于表示流结束的位置。 Trying to read from the MemoryStream again will not return any data, as the MemoryStream read/write position is at the end of the stream. 再次尝试从MemoryStream读取不会返回任何数据,因为MemoryStream的读/写位置位于流的末尾。

In your second approach, you passed the Input byte array as argument to the MemoryStream constructor. 在第二种方法中,您将Input字节数组作为参数传递给MemoryStream构造函数。 Providing the byte array through the constructor not only will make MemoryStream use this byte array, but more importantly it keeps the initial stream position of zero. 通过构造函数提供字节数组不仅会使MemoryStream使用此字节数组,而且更重要的是,它将初始流位置保持为零。 Thus, when trying to read from the MemoryStream initialized in this way, the data contained in the input byte array will be returned as expected. 因此,当尝试从以这种方式初始化的MemoryStream中读取数据时,将按预期返回包含在输入字节数组中的数据。


How to fix the problem with the first approach? 如何用第一种方法解决问题?

You can make the first approach with MemoryStream.Write working by simply setting the MemoryStream position back to the intended/original value (in your example case it would be zero) after writing the data to the MemoryStream: 您可以将MemoryStream.Write用作第一种方法,方法是将数据写入MemoryStream之后,只需将MemoryStream位置设置回预期/原始值(在您的示例中为零)即可:

byte[] Input;
using (MemoryStream mem = new MemoryStream())
{
    mem.Write(Input, 0, (int)Input.Length);

    mem.Position = 0;

    using (StreamReader stream = new StreamReader(mem))
    {
        ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM