在C#中,Stream
是一个抽象基类,用于处理输入和输出的字节序列。它是所有输入/输出 (I/O) 操作的基础,包括文件操作、网络操作、内存操作等。Stream
类提供了一组方法和属性,使得可以对数据进行读取、写入和定位。下面是一些Stream
类的基本使用方法:
- 创建一个
FileStream
并写入数据:
using System;
using System.IO;class Program
{static void Main(){// 创建文件流using (FileStream fs = new FileStream("data.txt", FileMode.Create)){// 将数据写入文件byte[] data = new byte[] { 65, 66, 67, 68, 69 };fs.Write(data, 0, data.Length);}}
}
- 读取
FileStream
中的数据:
using System;
using System.IO;class Program
{static void Main(){// 打开文件流using (FileStream fs = new FileStream("data.txt", FileMode.Open)){// 读取文件中的数据byte[] buffer = new byte[1024];int bytesRead = fs.Read(buffer, 0, buffer.Length);Console.WriteLine("Data read from file: " + Encoding.UTF8.GetString(buffer, 0, bytesRead));}}
}
- 使用
MemoryStream
进行内存操作:
using System;
using System.IO;class Program
{static void Main(){// 使用内存流写入数据using (MemoryStream ms = new MemoryStream()){byte[] data = new byte[] { 70, 71, 72, 73, 74 };ms.Write(data, 0, data.Length);// 读取内存流中的数据ms.Position = 0;byte[] buffer = new byte[1024];int bytesRead = ms.Read(buffer, 0, buffer.Length);Console.WriteLine("Data read from memory stream: " + Encoding.UTF8.GetString(buffer, 0, bytesRead));}}
}
上述示例演示了如何使用 FileStream
和 MemoryStream
进行基本的读取和写入操作。Stream
类还有许多其他派生类,如 NetworkStream
, CryptoStream
等,可根据不同的需求选择合适的流类型来进行I/O操作。