数智应用帮
柔彩主题三 · 更轻盈的阅读体验

C#开发读取文本文件的几种实用方法

发布时间:2026-01-09 06:51:45 阅读:43 次

在日常开发中,处理文本文件是很常见的需求。比如你写了个小工具,想把日志内容读出来分析,或者需要批量导入一些配置信息,这时候用 C# 来读取文本文件就特别方便。

使用 File.ReadAllText 一次性读取

如果你的文件不大,比如几KB到几百KB,可以直接一次性读完整个文件。这种方法最简单,适合读取日志、配置说明这类小文件。

using System;
using System.IO;

string path = @"C:\logs\app.log";
try {
    string content = File.ReadAllText(path);
    Console.WriteLine(content);
} catch (Exception ex) {
    Console.WriteLine("读取失败:" + ex.Message);
}

使用 File.ReadAllLines 按行读取

有些时候你希望一行一行地处理内容,比如读取一个名单或数据列表。File.ReadAllLines 会把每行内容放到字符串数组里,方便遍历。

using System;
using System.IO;

string path = @"C:\data\users.txt";
try {
    string[] lines = File.ReadAllLines(path);
    foreach (string line in lines) {
        Console.WriteLine("用户:" + line);
    }
} catch (IOException ex) {
    Console.WriteLine("文件操作出错:" + ex.Message);
}

使用 StreamReader 逐行读取大文件

当文件很大,比如超过几十MB,还用上面的方法可能会占用太多内存。这时候推荐用 StreamReader,它支持边读边处理,不会一下子把所有内容加载进内存。

using System;
using System.IO;

string path = @"C:\data\bigdata.txt";
try {
    using (StreamReader reader = new StreamReader(path)) {
        string line;
        while ((line = reader.ReadLine()) != null) {
            // 处理每一行
            Console.WriteLine(line);
        }
    }
} catch (FileNotFoundException) {
    Console.WriteLine("文件没找到,请检查路径");
} catch (UnauthorizedAccessException) {
    Console.WriteLine("没有权限访问该文件");
}

这种方式就像看小说时一页一页翻,而不是把整本书拍到脑子里。既省资源,又能稳定运行。

编码问题别忽略

有时候读出来的中文是乱码,多半是编码没对上。Windows 下记事本保存的文本默认可能是 GBK(即 GB2312),而 C# 默认按 UTF-8 处理。解决办法是在读取时指定正确的编码。

using System;
using System.IO;
using System.Text;

string path = @"C:\data\config.txt";
// 使用 GB2312 编码读取
using (StreamReader reader = new StreamReader(path, Encoding.GetEncoding("GB2312"))) {
    string content = reader.ReadToEnd();
    Console.WriteLine(content);
}

如果你不确定是什么编码,可以先用记事本打开文件,另存为时看看底部的编码选项。

小技巧:判断文件是否存在再读

程序运行时如果路径写错或文件被移动,直接读会报异常。提前判断一下更稳妥。

if (File.Exists(path)) {
    string content = File.ReadAllText(path);
    Console.WriteLine(content);
} else {
    Console.WriteLine("文件不存在:" + path);
}

这个习惯能让你的程序更健壮,避免一出错就崩溃。