如何使用 C# 读取 TXT 文件?使用 StreamReader(string path) 创建 StreamReader 对象。使用 ReadLine() 方法逐行读取文件。循环遍历文件内容,直到达到文件末尾(ReadLine() 返回 null)。使用 Dispose() 方法关闭 StreamReader 对象。

如何使用 C# 读取 TXT 文件
读取文本文件的基本步骤:
创建StreamReader对象:
StreamReader(string path)构造函数,其中path是文本文件的路径。读取文件内容:
ReadLine()方法逐行读取文件。ReadLine()返回 null)。关闭文件:
Dispose()方法关闭StreamReader对象。这样做可以释放系统资源。示例代码:
<code class="c#">using System;
using System.IO;
namespace ReadTextFile
{
class Program
{
static void Main(string[] args)
{
// 文件路径
string filePath = @"C:\path\to\text.txt";
try
{
// 创建StreamReader对象
using (StreamReader reader = new StreamReader(filePath))
{
// 逐行读取文件内容
while (true)
{
string line = reader.ReadLine();
if (line == null)
break;
// 处理每一行数据
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
Console.WriteLine("读取文件出错:" + e.Message);
}
}
}
}</code>其他注意事项:
File.ReadAllText()方法一次性读取整个文件。以上就是c#怎么读取txt文件的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号