How to read a txt file in C#?
In C#, you can use the StreamReader class to read a txt file. Here is an example code:
using System;
using System.IO;
class Program
{
static void Main()
{
try
{
// 指定txt文件的路径
string path = @"C:\example.txt";
// 创建一个StreamReader对象来读取文件
using (StreamReader sr = new StreamReader(path))
{
string line;
// 一次读取一行,直到文件的末尾
while ((line = sr.ReadLine()) != null)
{
// 打印每一行的内容
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
Console.WriteLine("读取文件出错:" + e.Message);
}
}
}
In the example above, we used the StreamReader class to open a txt file, then used the ReadLine method to read the file content line by line and printed each line to the console. It is important to note that after using the StreamReader, you should either use the using statement or manually call the Dispose method to release resources.