C#的streamreader如何用
StreamReader 类是用于读取字符流的抽象类。以下是使用 StreamReader 类的基本步骤:
1. 导入命名空间:
```csharp
using System.IO;
```
2. 创建 StreamReader 对象:
```csharp
StreamReader reader = new StreamReader("文件路径");
```
3. 使用 StreamReader 对象读取数据:
```csharp
string line = reader.ReadLine(); // 读取一行数据
string content = reader.ReadToEnd(); // 读取所有数据
```
4. 关闭 StreamReader 对象:
```csharp
reader.Close();
```
完全的示例代码以下:
```csharp
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
try
{
StreamReader reader = new StreamReader("文件路径");
// 逐行读取数据
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
reader.Close();
}
catch (Exception e)
{
Console.WriteLine("读取文件时产生毛病:" + e.Message);
}
}
}
```
请将上述代码中的 "文件路径" 替换为实际的文件路径,然后可使用 StreamReader 对象读取文件内容。
TOP