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
相关推荐
郭涤生11 分钟前
不同主机之间网络通信-以太网连接复习
开发语言·rk3588
山居秋暝LS16 分钟前
【无标题】RTX00安装paddle OCR,win11不能装最新的,也不能用GPU
开发语言·r语言
卢锡荣20 分钟前
单芯通吃,盲插标杆 —— 乐得瑞 LDR6020,Type‑C 全场景互联 “智慧芯”
c语言·开发语言·计算机外设
Xin_ye1008624 分钟前
C# 零基础到精通教程 - 第七章:面向对象编程(入门)——类与对象
开发语言·c#
rockey62730 分钟前
AScript异步执行与await关键字
c#·.net·script·eval·expression·异步执行·动态脚本
AI科技星1 小时前
《数学公理体系·第三部·数术几何》(2026 年版)
c语言·开发语言·线性代数·算法·矩阵·量子计算·agi
审判长烧鸡1 小时前
【Go工具】go-playground是什么组织?官方的?
开发语言·安全·go
kkeeper~1 小时前
0基础C语言积跬步之字符函数与字符串函数(上)
c语言·开发语言
hhb_6182 小时前
Swift核心技术难点与实战案例解析
开发语言·ios·swift
一楼的猫2 小时前
从工具链视角对比:番茄作家助手 vs 第三方写作辅助方案
java·服务器·开发语言·前端·学习·chatgpt·ai写作