一、在C#语言中,可以使用 StreamReader 类来读取 txt 文件。
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "your_file_path.txt"; // 将这里替换为您实际的文件路径
try
{
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine())!= null)
{
Console.WriteLine(line); // 可以根据需要对读取的每行内容进行处理
}
}
}
catch (FileNotFoundException)
{
Console.WriteLine("文件未找到!");
}
catch (IOException e)
{
Console.WriteLine("发生 I/O 错误: " + e.Message);
}
}
}
以上代码中:
- StreamReader :类用于从文本文件中以一种方便的方式读取字符数据。
- reader:这是创建的 StreamReader 对象的名称,通过这个名称可以调用 StreamReader 类提供的方法来操作文件的读取。
- new StreamReader(filePath):这里使用 new 关键字创建了一个 StreamReader 对象;filePath :通常是一个表示文件路径的字符串。
使用 reader 对象,可以通过以下常见的方法来读取文件的内容:
- ReadLine():读取文件的一行内容,并返回一个字符串。
- ReadToEnd():读取文件的全部内容,并返回一个字符串。
二、另外,还可以一次性读取整个文件的内容,如下所示:
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "your_file_path.txt"; // 替换为实际路径
try
{
using (StreamReader reader = new StreamReader(filePath))
{
string content = reader.ReadToEnd();
Console.WriteLine(content); // 对读取的全部内容进行处理
}
}
catch (FileNotFoundException)
{
Console.WriteLine("文件未找到!");
}
catch (IOException e)
{
Console.WriteLine("发生 I/O 错误: " + e.Message);
}
}
}