1.MemoryStream简介 2.MemoryStream常用方法和属性 1.MemoryStream简介 MemoryStream是C#中System. IO 命名空间下的一个类, 它将数据存储在内存中, 而非磁盘文件, 因此读写速度极快, 适合临 时处理小量数据( 如序列化/ 反序列化、网络数据中转、内存中操作字节数组等) 简单来说: a. 普通FileStream操作的是磁盘文件, MemoryStream操作的是内存中的字节数组 b. 用完后需及时释放内存( 通过using 语句自动释放) 2.MemoryStream常用方法和属性 1 ) . 核心属性 a. Position 当前流的读写位置( 必须重置到0 才能读取刚写入的数据, 否则从末尾开始读) b. Length 流中存储的字节总数 c. Capacity 流的内存容量( 可自动扩容, 也可手动指定) 2 ) . 核心方法 a. Write ( byte [ ] buffer, int offset, int count) 将字节数组写入流( offset 是起始索引, count是写入长度) b. Read ( byte [ ] buffer, int offset, int count) 从流读取字节到数组( 返回实际读取的字节数) c. ToArray ( ) 将流中所有数据转为字节数组 d. GetBuffer ( ) 获取流的底层字节数组( 包含未使用的容量) e. Flush ( ) 清空流缓冲区( MemoryStream中无实际作用, 仅为实现抽象类) f. Close ( ) / Dispose ( ) 释放资源( using 语句会自动调用)
using System ; using System. IO ; using System. Text ; class MemoryStreamDemo { static void Main ( ) { // 1. 基础用法:写入字符串到 MemoryStream,再读取出来 // 定义要写入的字符串 string originalText= "Hello, MemoryStream!" ; // 将字符串转为字节数组(指定编码,避免乱码) byte [ ] inputBytes= Encoding. UTF8. GetBytes ( originalText) ; // using 语句自动释放资源(关键:避免内存泄漏) using ( MemoryStream ms= new MemoryStream ( ) ) { // 2. 写入字节数组到 MemoryStream ms. Write ( inputBytes, 0 , inputBytes. Length) ; // 3. 重置流的位置到起始处(否则读取时会从末尾开始,读不到数据) ms. Position= 0 ; // 4. 从 MemoryStream 读取数据到新的字节数组 byte [ ] outputBytes= new byte [ ms. Length] ; int bytesRead= ms. Read ( outputBytes, 0 , outputBytes. Length) ; // 5. 将字节数组转回字符串 string readText= Encoding. UTF8. GetString ( outputBytes, 0 , bytesRead) ; Console. WriteLine ( "读取到的内容:" + readText) ; // 输出:Hello, MemoryStream! // 6. 快捷获取 MemoryStream 中的所有字节(替代手动读取) byte [ ] allBytes= ms. ToArray ( ) ; Console. WriteLine ( "字节数组长度:" + allBytes. Length) ; // 输出:20(对应字符串的UTF8字节数) } // 7. 进阶:初始化时传入字节数组(只读/可写) byte [ ] initBytes= Encoding. UTF8. GetBytes ( "初始化的字节数组" ) ; // 创建基于现有字节数组的 MemoryStream(可写) using ( MemoryStream ms2= new MemoryStream ( initBytes) ) { // 追加写入数据 byte [ ] appendBytes= Encoding. UTF8. GetBytes ( " - 追加内容" ) ; ms2. Write ( appendBytes, 0 , appendBytes. Length) ; // 重置位置后读取全部 ms2. Position= 0 ; string fullText= new StreamReader ( ms2) . ReadToEnd ( ) ; Console. WriteLine ( "追加后的内容:" + fullText) ; // 输出:初始化的字节数组 - 追加内容 } } }