使用 C# 逐行读取文本文件的代码

以下是使用 C# 逐行读取文本文件的代码示例:


```csharp
string filePath = "path/to/file.txt";


try
{
    using (StreamReader reader = new StreamReader(filePath))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            Console.WriteLine(line);
        }
    }
}
catch (IOException e)
{
    Console.WriteLine("An error occurred while reading the file: " + e.Message);
}
```


在上面的示例中,我们使用 `StreamReader` 类以逐行的方式读取指定路径的文本文件。在 `while` 循环中,每次调用 `reader.ReadLine()` 都会读取文件的下一行,并将其赋值给变量 `line`。只要 `line` 不为 `null`,就表示还有未读取的行,我们将其打印到控制台。


请确保将 `"path/to/file.txt"` 替换为实际的文件路径,并根据需要进行其他处理或操作。


在使用 `StreamReader` 时,需要注意适当处理资源释放。在上面的示例中,我们使用 `using` 语句来自动处理 `StreamReader` 对象的释放,以确保在读取完文件后,文件句柄得到正确的释放。


希望这个示例能够帮助你逐行读取文本文件。如果有任何进一步的问题,请随时提问。