C# 文件读取
文件读取是指使用 C# 程序从计算机文件系统中获取文件内容的过程。将存储在磁盘上的文件内容加载到内存中,供程序处理。主要类型有:文本文件读取(如 .txt, .csv, .json, .xml);二进制文件读取(如 .jpg, .png, .exe)。
同步方法
File
ReadAllText
是 C# 中一个简单易用的文件写入方法,它会创建新文件,如果文件已存在则覆盖。
string path = @"D:\CSharpProject\File\MyTest.txt";
string str = File.ReadAllText(path);
ReadLines
获取文件中每行数据组成的集合
string path = @"D:\CSharpProject\File\MyTest.txt";
var list = File.ReadLines(path).ToList();
Console.WriteLine(string.Join(",", list));
ReadAllLines
会一次性将整个文本文件的所有行读取到一个字符串数组中。
string path = @"D:\CSharpProject\File\MyTest.txt";
string[] list = File.ReadAllLines(path);
Console.WriteLine(string.Join(",", list));
ReadAllBytes
一个用于读取二进制文件的方法,它会将整个文件内容读取到一个字节数组中。
string path = @"D:\CSharpProject\File\MyTest.txt";
byte[] str = File.ReadAllBytes(path);
StreamReader
StreamReader 是 System.IO 命名空间中的一个类,专门用于从流(如文件流)中读取字符数据。它提供了高效的文本读取能力,特别适合处理大型文本文件。
方法 | 描述 |
---|---|
Read() | 读取下一个字符 |
ReadLine() | 读取一行字符 |
ReadToEnd() | 读取从当前位置到流末尾的所有内容 |
简单使用
string path = @"D:\CSharpProject\File\MyTest.txt";
using (StreamReader reader = new StreamReader(path))
{string content = reader.ReadToEnd();Console.WriteLine(content);
}
逐行读取
using (StreamReader reader = new StreamReader("data.txt"))
{string line;while ((line = reader.ReadLine()) != null){Console.WriteLine(line);}
}
读取特定数量字符
char[] buffer = new char[100];
using (StreamReader reader = new StreamReader("file.txt"))
{int charsRead = reader.Read(buffer, 0, buffer.Length);string result = new string(buffer, 0, charsRead);
}
FileStream
FileStream 是 System.IO 命名空间中的一个类,提供了对文件进行低级读写操作的能力。与更高级的 StreamReader/StreamWriter 相比,FileStream 提供了更底层的控制,适合处理二进制文件或需要精细控制文件操作的场景。
using System.IO;string filePath = "example.bin";// 使用 using 语句确保资源被正确释放
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{byte[] buffer = new byte[fileStream.Length];int bytesRead = fileStream.Read(buffer, 0, buffer.Length);Console.WriteLine($"读取了 {bytesRead} 字节");// 处理 buffer 中的数据...
}
异步方法
File
ReadAllTextAsync
是ReadAllText的异步实现,功能相同,不会阻塞主线程。
using System.IO;
using System.Threading.Tasks;public async Task<string> ReadFileContentAsync(string filePath)
{return await File.ReadAllTextAsync(filePath);
}
ReadAllLinesAsync
是ReadAllLines的异步实现,功能相同,不会阻塞主线程。
using System.IO;
using System.Threading.Tasks;public async Task<string[]> ReadFileAsync(string filePath)
{return await File.ReadAllLinesAsync(filePath);
}
ReadAllBytesAsync
是ReadAllBytes的异步实现,功能相同,不会阻塞主线程
using System.IO;
using System.Threading.Tasks;public async Task<byte[]> ReadBinaryFileAsync(string filePath)
{return await File.ReadAllBytesAsync(filePath);
}
StreamReader
简单使用
using System.IO;
using System.Threading.Tasks;async Task<string> ReadFileAllTextAsync(string filePath)
{using (StreamReader reader = new StreamReader(filePath)){return await reader.ReadToEndAsync();}
}
异步逐行读取文件
using (StreamReader reader = new StreamReader("data.txt"))
{string line;while ((line = reader.ReadLine()) != null){Console.WriteLine(line);}
}
异步读取指定数量字符
async Task<string> ReadChunkAsync(string path, int chunkSize)
{using (var reader = new StreamReader(path)){char[] buffer = new char[chunkSize];int bytesRead = await reader.ReadBlockAsync(buffer, 0, chunkSize);return new string(buffer, 0, bytesRead);}
}
FileStream
using System.IO;
using System.Threading.Tasks;async Task<byte[]> ReadFileFullyAsync(string filePath)
{using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, FileOptions.Asynchronous)) // 关键选项{byte[] buffer = new byte[fs.Length];await fs.ReadAsync(buffer, 0, buffer.Length);return buffer;}
}
对比
方法 | 特点 | 适用场景 | 内存效率 | 异步支持 | 典型文件大小 |
---|---|---|---|---|---|
File.ReadAllText | 一次性读取全部文本 | 小文本文件处理 | 低 | 无 | <10MB |
File.ReadAllTextAsync | 异步读取全部文本 | UI应用读取小文本 | 低 | 有 | <10MB |
File.ReadAllLines | 按行读取为数组 | 需要行处理的小文件 | 低 | 无 | <10MB |
File.ReadAllLinesAsync | 异步按行读取 | UI应用需要行处理 | 低 | 有 | <10MB |
File.ReadAllBytes | 读取二进制数据 | 图片/音频等二进制文件 | 低 | 无 | <50MB |
File.ReadAllBytesAsync | 异步读取二进制 | UI应用处理二进制 | 低 | 有 | <50MB |
File.ReadLines | 延迟行迭代 | 大文本文件处理 | 高 | 无 | 10MB+ |
StreamReader | 灵活文本读取 | 需要控制读取过程 | 高 | 有(Async方法) | 任意大小 |
FileStream | 底层二进制读取 | 大文件/随机访问 | 高 | 有 | 任意大小 |
选择参考
参考项 | 推荐方法 | 场景举例 |
小文本文件处理 ( < 1MB ) | ReadAllText ReadAllTextAsync ReadAllLines ReadAllLinesAsync | 配置文件读取 小型JSON/XML文件解析 模板文件加载 |
大文本文件处理 ( > 10MB ) | File.ReadLines (LINQ兼容) StreamReader (逐行处理) StreamReader.ReadLineAsync (异步逐行) | 日志文件分析 大型CSV数据处理 文本文件实时监控 |
二进制文件处理 | File.ReadAllBytes / ReadAllBytesAsync (小文件) FileStream (大文件) | 图片/音视频处理 文件加密/解密 自定义二进制格式解析 |
同步和异步选择
-
使用同步方法:
-
简单的控制台应用程序
-
需要简单快速完成的小文件操作
-
在后台线程中执行的文件操作
-
-
使用异步方法:
-
UI应用程序(避免界面冻结)
-
Web应用程序和服务(提高并发处理能力)
-
大文件操作(避免阻塞主线程)
-
需要响应性的应用程序
-