StreamReader 读取Txt文件
时间: 2023-06-23 12:59:44 浏览: 49
可以使用 .NET Framework 中的 StreamReader 类来读取文本文件。以下是一个示例代码:
```csharp
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string filePath = @"C:\example.txt";
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
```
在示例代码中,首先需要指定要读取的文本文件的路径。然后使用 `StreamReader` 类创建一个文件读取器,并使用 `using` 语句确保文件读取器在使用结束后被正确地释放。在 `while` 循环中,使用 `ReadLine()` 方法逐行读取文件内容,并将每行内容输出到控制台上。
相关问题
c#streamreader读取txt
C#的StreamReader是一个用于读取文本文件的类。它提供了一种方便的方式来逐行读取文本数据。你可以使用StreamReader来打开一个文本文件,并逐行读取其中的内容。
下面是一个使用StreamReader读取文本文件的简单示例代码:
```csharp
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "example.txt";
c#读取txt文件数据
可以使用C#中的File类和StreamReader类来读取txt文件数据。具体步骤如下:
1. 引入命名空间using System.IO;
2. 定义一个StreamReader对象,用于读取txt文件中的数据,代码如下:StreamReader sr = new StreamReader("D:\\test.txt", Encoding.Default);(这里假设要读取的txt文件路径为D:\test.txt,编码方式为默认编码)
3. 使用sr对象的ReadLine()方法来逐行读取txt文件中的数据,代码如下:string line = sr.ReadLine();
4. 读取完毕后,使用sr对象的Close()方法来关闭文件,代码如下:sr.Close();
完整代码示例:
```
using System.IO;
//...
string filePath = "D:\\test.txt";
StreamReader sr = new StreamReader(filePath, Encoding.Default);
string line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
sr.Close();
```