C# 读取txt 文本
时间: 2024-09-20 14:02:46 浏览: 55
在C#中,你可以使用System.IO命名空间下的StreamReader类来读取.txt文本文件。以下是一个基本步骤:
1. 首先,你需要创建一个StreamReader对象,并指定你要读取的文件路径。假设文件名为"example.txt",放在项目目录下。
```csharp
using System;
using System.IO;
string filePath = "example.txt";
```
2. 使用`File.OpenText()`方法打开文件并获取可读流:
```csharp
StreamReader reader = new StreamReader(filePath);
```
3. 然后,你可以通过`ReadLine()`方法逐行读取文件内容,直到文件结束:
```csharp
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line); // 打印每一行内容
}
```
4. 最后别忘了关闭文件流,释放资源:
```csharp
reader.Close();
```
如果你想要一次性读取整个文件的内容,可以将所有行保存到字符串变量中:
```csharp
StringBuilder sb = new StringBuilder();
sb.AppendLine(reader.ReadToEnd());
string fileContent = sb.ToString();
```
阅读全文
相关推荐
















