怎么读取MemoryStream数据
时间: 2024-03-13 13:42:31 浏览: 106
使用 MemoryStream 读取数据可以使用 BinaryReader 或者 StreamReader 类。下面是两种读取方式的示例:
1. 使用 BinaryReader 读取 MemoryStream 数据
```csharp
MemoryStream ms = new MemoryStream();
BinaryWriter bw = new BinaryWriter(ms);
bw.Write("Hello World");
bw.Flush();
ms.Position = 0; // 重置流的位置
BinaryReader br = new BinaryReader(ms);
string message = br.ReadString();
Console.WriteLine(message); // 输出 "Hello World"
```
这个示例首先创建了一个 MemoryStream 对象,并使用 BinaryWriter 写入了字符串 "Hello World"。然后将流的位置重置为 0,并使用 BinaryReader 读取数据。最后将读取到的字符串输出到控制台。
2. 使用 StreamReader 读取 MemoryStream 数据
```csharp
MemoryStream ms = new MemoryStream();
StreamWriter sw = new StreamWriter(ms);
sw.Write("Hello World");
sw.Flush();
ms.Position = 0; // 重置流的位置
StreamReader sr = new StreamReader(ms);
string message = sr.ReadToEnd();
Console.WriteLine(message); // 输出 "Hello World"
```
这个示例首先创建了一个 MemoryStream 对象,并使用 StreamWriter 写入了字符串 "Hello World"。然后将流的位置重置为 0,并使用 StreamReader 读取数据。最后将读取到的字符串输出到控制台。
需要注意的是,在使用 MemoryStream 读取数据时,需要将流的位置重置为 0,以便从流的开头开始读取数据。与 BinaryReader 和 StreamReader 不同的是,MemoryStream 不需要手动释放资源,因为当流对象被销毁时,它所包含的内存将会被自动释放。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)