在 C# 中,从文本文件(txt)读取数据是常见的 I/O 操作,涉及文件系统访问和数据处理。.NET 提供了多种类和方法来实现这一功能。
最简单的方法,一次性读取整个文件内容为字符串。
string filePath = @"C:\example\data.txt";
string content = File.ReadAllText(filePath);
Console.WriteLine(content);
优点:
缺点:
读取所有行到字符串数组中,每行一个元素。
string[] lines = File.ReadAllLines(filePath);
foreach (string line in lines)
{
Console.WriteLine(line);
}
优点:
逐行读取,内存效率高,适合大文件。
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
优点:
延迟加载,适合需要 LINQ 查询的场景。
IEnumerable<string> lines = File.ReadLines(filePath);
var filteredLines = lines.Where(line => line.Contains("keyword"));
foreach (string line in filteredLines)
{
Console.WriteLine(line);
}
优点:
if (File.Exists(filePath))
{
// 读取文件
}
else
{
Console.WriteLine("文件不存在");
}
指定正确的编码格式:
string content = File.ReadAllText(filePath, Encoding.UTF8);
使用 StreamReader 逐行读取,避免内存溢出。
确保文件未被其他进程锁定,或使用 try-catch 处理异常。
using System;
using System.IO;
using System.Text;
class Program
{
static void Main()
{
string filePath = @"C:\data\example.txt";
try
{
// 方法1: 读取全部内容
Console.WriteLine("--- 全部内容 ---");
string allText = File.ReadAllText(filePath, Encoding.UTF8);
Console.WriteLine(allText);
// 方法2: 逐行读取
Console.WriteLine("\n--- 逐行读取 ---");
using (StreamReader reader = new StreamReader(filePath))
{
int lineNumber = 1;
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine($"{lineNumber}: {line}");
lineNumber++;
}
}
// 方法3: 使用LINQ处理
Console.WriteLine("\n--- 包含'a'的行 ---");
var linesWithA = File.ReadLines(filePath)
.Where(l => l.Contains("a"));
foreach (var line in linesWithA)
{
Console.WriteLine(line);
}
}
catch (FileNotFoundException)
{
Console.WriteLine("文件未找到");
}
catch (IOException ex)
{
Console.WriteLine($"IO异常: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"发生错误: {ex.Message}");
}
}
}
这个示例展示了三种常见的读取文本文件的方法,并包含了基本的错误处理。
没有搜到相关的文章