C#使用MemoryStream类读写内存

时间:2023-03-08 23:04:02
C#使用MemoryStream类读写内存

MemoryStream和BufferedStream都派生自基类Stream,因此它们有很多共同的属性和方法,但是每一个类都有自己独特的用法。这两个类都是实现对内存进行数据读写的功能,而不是对持久性存储器进行读写。

读写内存-MemoryStream类

MemoryStream类用于向内存而不是磁盘读写数据。MemoryStream封装以无符号字节数组形式存储的数据,该数组在创建MemoryStream对象时被初始化,或者该数组可创建为空数组。可在内存中直接访问这些封装的数据。内存流可降低应用程序中对临时缓冲区和临时文件的需要。

下表列出了MemoryStream类的重要方法:

1、Read():读取MemoryStream流对象,将值写入缓存区。

2、ReadByte():从MemoryStream流中读取一个字节。

3、Write():将值从缓存区写入MemoryStream流对象。

4、WriteByte():从缓存区写入MemoytStream流对象一个字节。

Read方法使用的语法如下:

mmstream.Read(byte[] buffer,offset,count) 

其中mmstream为MemoryStream类的一个流对象,3个参数中,buffer包含指定的字节数组,该数组中,从offset到(offset +count-1)之间的值由当前流中读取的字符替换。Offset是指Buffer中的字节偏移量,从此处开始读取。Count是指最多读取的字节数。Write()方法和Read()方法具有相同的参数类型。

MemoryStream类的使用实例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; namespace ConsoleApplication1
{
class Program
{
static void Main()
{
int count;
byte[] byteArray;
char[] charArray;
UnicodeEncoding uniEncoding = new UnicodeEncoding();
// Create the data to write to the stream.
byte[] firstString = uniEncoding.GetBytes("一二三四五");
byte[] secondString = uniEncoding.GetBytes("上山打老虎");
using (MemoryStream memStream = new MemoryStream())
{
// Write the first string to the stream.
memStream.Write(firstString, , firstString.Length); // Write the second string to the stream, byte by byte.
count = ;
while (count < secondString.Length)
{
memStream.WriteByte(secondString[count++]);
} // Write the stream properties to the console.
Console.WriteLine("Capacity={0},Length={1},Position={2}\n", memStream.Capacity.ToString(), memStream.Length.ToString(), memStream.Position.ToString()); // Set the position to the beginning of the stream.
memStream.Seek(, SeekOrigin.Begin); // Read the first 20 bytes from the stream.
byteArray = new byte[memStream.Length];
count = memStream.Read(byteArray, , ); // Read the remaining bytes, byte by byte.
while (count < memStream.Length)
{
byteArray[count++] = Convert.ToByte(memStream.ReadByte());
} // Decode the byte array into a char array
// and write it to the console.
charArray = new char[uniEncoding.GetCharCount(byteArray, , count)];
uniEncoding.GetDecoder().GetChars(byteArray, , count, charArray, );
Console.WriteLine(charArray); Console.ReadKey();
}
}
}
}