C# 读取文件方法介绍

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


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

csharp 复制代码
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(按行读取为数组)

csharp 复制代码
string[] lines = File.ReadAllLines(path);
foreach (string line in lines)
{
    Console.WriteLine(line);
}

特点

✅ 分行处理,适合日志文件

❌ 同样全量加载,内存压力大


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

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

特点

内存效率高 ,适合大文件

🔥 推荐用于日志文件、大型CSV


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

csharp 复制代码
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卡顿)

csharp 复制代码
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(超大型文件,内存映射)

csharp 复制代码
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程序
MemoryMapped GB+ 极低 超大文件

⚠️ 注意事项

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

🔥 最佳实践

  • 小型文本File.ReadAllText
  • 大型文本StreamReader + while
  • 二进制数据FileStream
  • UI程序async/await + ReadToEndAsync
  • GB级文件MemoryMappedFile
相关推荐
cch89183 小时前
汇编与Java:底层与高层的编程对决
java·开发语言·汇编
荒川之神4 小时前
拉链表概念与基本设计
java·开发语言·数据库
chushiyunen4 小时前
python中的@Property和@Setter
java·开发语言·python
小樱花的樱花4 小时前
C++ new和delete用法详解
linux·开发语言·c++
froginwe114 小时前
C 运算符
开发语言
fengfuyao9855 小时前
低数据极限下模型预测控制的非线性动力学的稀疏识别 MATLAB实现
开发语言·matlab
摇滚侠5 小时前
搭建前端开发环境 安装 nodejs 设置淘宝镜像 最简化最标准版本 不使用 NVM NVM 高版本无法安装低版本 nodejs
java·开发语言·node.js
t198751285 小时前
MATLAB十字路口车辆通行情况模拟系统
开发语言·matlab
weixin_408099675 小时前
图片去水印 API 接口实战:网站如何实现自动去水印(Python / PHP / C#)
图像处理·人工智能·python·c#·php·api·图片去水印
yyk的萌5 小时前
AI 应用开发工程师基础学习计划
开发语言·python·学习·ai·lua