在C#中读取文件的六种主流方法详解

 更新时间:2025年11月23日 14:00:10   作者:降薪码农  
在 C# 中读取文件有多种方法,不同方式适用于不同场景(小型文件、大型文件、文本文件或二进制文件),本文给大家介绍了 6 种主流方法以及其适用场景,需要的朋友可以参考下

在 C# 中读取文件有多种方法,不同方式适用于不同场景(小型文件、大型文件、文本文件或二进制文件)。以下是 6 种主流方法及其适用场景:

方法1:File.ReadAllText(读取整个文本文件)

string path = @"C:\Example\test.txt";
try
{
    string content = File.ReadAllText(path);
    Console.WriteLine(content);
}
catch (IOException ex)
{
    Console.WriteLine($"读取失败: {ex.Message}");
}

特点

  • 超简单,单行代码读取全部
  • 仅适合小型文件(全部加载到内存)
  • 适用于配置文件、JSON等小文件

方法2:File.ReadAllLines(按行读取为数组)

string[] lines = File.ReadAllLines(path);
foreach (string line in lines)
{
    Console.WriteLine(line);
}

特点

  • 分行处理,适合日志文件
  • 同样全量加载,内存压力大

方法3:StreamReader(逐行读取,内存友好)

using (StreamReader reader = new StreamReader(path))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line); // 逐行处理
    }
}

特点

  • 内存效率高,适合大文件
  • 推荐用于日志文件、大型CSV

方法4:FileStream(二进制/字节读取)

byte[] buffer = new byte[1024];
using (FileStream fs = new FileStream(path, FileMode.Open))
{
    int bytesRead;
    while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
    {
        string chunk = Encoding.UTF8.GetString(buffer, 0, bytesRead);
        Console.Write(chunk);
    }
}

特点

  • 适合二进制文件(如图片、视频)
  • 可控缓冲区大小

方法5:async/await(异步读取,避免UI卡顿)

async Task ReadFileAsync(string path)
{
    using (StreamReader reader = new StreamReader(path))
    {
        string content = await reader.ReadToEndAsync();
        Console.WriteLine(content);
    }
}

// 调用
await ReadFileAsync(@"C:\largefile.txt");

特点

  • 不阻塞UI线程,WinForms/WPF必备
  • 适合网络磁盘文件

方法6:MemoryMappedFile(超大型文件,内存映射)

using (var mmf = MemoryMappedFile.CreateFromFile(path))
{
    using (var stream = mmf.CreateViewStream())
    {
        byte[] buffer = new byte[1024];
        stream.Read(buffer, 0, buffer.Length);
        string text = Encoding.UTF8.GetString(buffer);
        Console.WriteLine(text);
    }
}

特点

  • 处理GB级文件(如数据库文件)
  • 高级场景使用

方法对比表

方法适用文件大小内存占用速度适用场景
ReadAllText<10MB配置文件
ReadAllLines<10MB日志分析
StreamReader任意大型文本
FileStream任意可控二进制文件
async/await任意依实现UI程序
MemoryMappedGB+极低超大文件

注意事项

  1. 异常处理:始终用 try-catch 捕获 FileNotFoundException 或 IOException
  2. 路径安全
string safePath = Path.Combine("C:", "Folder", "file.txt"); // 避免手写路径
  • 编码问题:指定正确的编码(如中文用 Encoding.UTF8
File.ReadAllText(path, Encoding.GetEncoding("GB2312"));
  • 资源释放:必须用 using 或手动释放 FileStream/StreamReader

最佳实践

  • 小型文本 → File.ReadAllText
  • 大型文本 → StreamReader + while
  • 二进制数据 → FileStream
  • UI程序 → async/await + ReadToEndAsync
  • GB级文件 → MemoryMappedFile

以上就是在C#中读取文件的六种主流方法详解的详细内容,更多关于C#读取文件的资料请关注脚本之家其它相关文章!

相关文章

最新评论