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}\n", 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(); } } } }
分类:
C#
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构