使用 StreamReader 类打开、读取和关闭文本文件,使用 ReadLine 方法逐行读取文本文件,ReadToEnd方法将文本文件读取到末尾。写一段程序
时间: 2024-10-09 14:11:57 浏览: 48
在C#中,你可以使用`StreamReader`类来处理文本文件。以下是一个简单的示例程序,它演示了如何打开文件、读取内容并关闭文件:
```csharp
using System;
using System.IO;
class Program
{
static void Main()
{
// 定义文件路径
string filePath = "C:\\example.txt";
try
{
// 打开文件,如果不存在则创建
using (StreamReader reader = new StreamReader(filePath))
{
Console.WriteLine("Reading file line by line:");
// 逐行读取文件
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
// 或者一次性读取整个文件内容
// string content = reader.ReadToEnd();
// Console.WriteLine("Whole file content: " + content);
Console.WriteLine("\nFinished reading. Press any key to close the file.");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
// 关闭文件,无论是否成功读取都应确保资源释放
Console.WriteLine("File has been closed.");
}
}
}
```
在这个例子中,我们首先尝试打开文件,并在一个`using`块中操作,这样可以确保在读取完成后自动关闭文件,无需手动调用`Close`方法。我们通过`ReadLine`方法逐行读取,也可以选择用`ReadToEnd`方法获取所有内容。如果在读取过程中发生错误,会被catch块捕获并显示错误信息。
阅读全文
相关推荐


















