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(100))
            { 
                // Write the first string to the stream.
                memStream.Write(firstString, 0, firstString.Length); 
 
                // Write the second string to the stream, byte by byte.
                count = 0;
                while (count < secondString.Length) 
                {
                    memStream.WriteByte(secondString[count++]); 
                } 
 
                // Write the stream properties to the console.
                Console.WriteLine("Capacity={0},Length={1},Position={2}
", memStream.Capacity.ToString(), memStream.Length.ToString(), memStream.Position.ToString());
 
                // Set the position to the beginning of the stream.
                memStream.Seek(0, SeekOrigin.Begin);
 
                // Read the first 20 bytes from the stream.
                byteArray = new byte[memStream.Length]; 
                count = memStream.Read(byteArray, 0, 20); 
 
                // 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, 0, count)]; 
                uniEncoding.GetDecoder().GetChars(byteArray, 0, count, charArray, 0); 
                Console.WriteLine(charArray); Console.ReadKey();
            }
        }
    }
}
原文地址:https://www.cnblogs.com/niyl/p/10136912.html