C#中的文件和流操作主要通过
System.IO命名空间中的类来实现。这些类提供了对文件、目录、数据流的读写和管理能力,适用于文本文件、二进制文件以及内存中数据的处理。下面介绍几个核心类及其常见用法。
File 和 FileInfo:文件级操作
File 是静态类,适合一次性文件操作;FileInfo 是实例类,适合多次操作同一文件。
常用功能包括创建、复制、删除、移动和检查文件是否存在:
File.Exists(path):判断文件是否存在
File.WriteAllText(path, content):写入文本(覆盖)
File.ReadAllText(path):读取全部文本内容
File.Copy(source, dest):复制文件
File.Delete(path):删除文件
示例:
if (File.Exists("data.txt"))
{
string content = File.ReadAllText("data.txt");
File.WriteAllText("backup.txt", content);
}
Directory 和 DirectoryInfo:目录管理
Directory 提供静态方法管理文件夹;DirectoryInfo 支持更精细的操作。
常见用途:
Directory.CreateDirectory(path):创建目录
Directory.GetDirectories(path):获取子目录列表
Directory.GetFiles(path):获取目录下所有文件
Directory.Delete(path, true):递归删除目录
示例:
Directory.CreateDirectory("logs");
string[] files = Directory.GetFiles("logs", "*.log");
FileStream:底层字节流操作
FileStream 允许以字节方式读写文件,适合大文件或二进制数据。
可指定访问模式(读、写、追加)和共享方式。
使用new FileStream(path, FileMode.Open)打开文件 StreamReader 或
BinaryReader提高效率
示例:读取二进制文件
using (var fs = new FileStream("image.jpg", FileMode.Open))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
// 处理字节数组
}
StreamReader / StreamWriter:文本读写
这两个类用于高效处理字符数据,默认使用UTF-8编码。
StreamReader.ReadLine():逐行读取
StreamWriter.WriteLine():写入一行文本 支持 using 语句自动释放资源
示例:按行处理日志文件
using (var reader = new StreamReader("log.txt"))
using (var writer = new StreamWriter("filtered.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line.Contains("ERROR"))
writer.WriteLine(line);
}
}
MemoryStream:内存中的流操作
MemoryStream 将字节数组当作流使用,常用于临时存储或网络传输前的数据准备。
避免频繁磁盘I/O 可与BinaryReader/
BinaryWriter结合使用
示例:
var ms = new MemoryStream();
var writer = new BinaryWriter(ms);
writer.Write("Hello in memory");
byte[] data = ms.ToArray(); // 获取结果
基本上就这些。掌握这些类的使用,就能应对大多数C#文件和流操作需求。关键是根据场景选择合适的方式:简单操作用 File/Directory,大量文本用 StreamReader/Writer,二进制数据用 FileStream + BinaryReader,内存处理用 MemoryStream。注意始终正确释放资源,推荐使用
using语句。不复杂但容易忽略细节,比如编码问题或文件锁。
