C#打开TXT文件读取文本
时间: 2023-08-03 19:42:58 浏览: 710
可以使用C#的System.IO命名空间中的StreamReader类来打开并读取文本文件中的内容。以下是一个示例代码:
```
using System.IO;
string filePath = "C:\\example.txt";
string fileContent;
//打开文件并读取内容
using (StreamReader reader = new StreamReader(filePath))
{
fileContent = reader.ReadToEnd();
}
//输出文件内容
Console.WriteLine(fileContent);
```
需要注意的是,需要指定正确的文件路径,并且在读取完文件内容后需要关闭StreamReader对象。
相关问题
C# 打开txt文件
在C#中,你可以使用`System.IO.File`类或者`StreamReader`类来打开文本文件(txt文件)。这里是一个基本的例子:
```csharp
using System;
using System.IO;
public class MainClass {
public static void Main(string[] args) {
try {
// 指定文件路径
string filePath = "C:\\example\\test.txt";
// 使用FileStream打开文件
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) {
// 创建StreamReader实例并读取文件内容
using (StreamReader reader = new StreamReader(fileStream)) {
string line;
while ((line = reader.ReadLine()) != null) {
Console.WriteLine(line);
}
}
}
} catch (Exception ex) {
Console.WriteLine($"发生错误: {ex.Message}");
}
}
}
```
在这个例子中,首先尝试打开指定路径的txt文件,并使用`StreamReader`逐行读取文件内容。注意要在`try-catch`块中处理可能出现的异常。
c#中txt文件读写
### C# 中的 TXT 文件读取和写入
#### 读取 TXT 文件
为了从指定路径读取整个文本文件的内容,在 C# 中可以使用 `StreamReader` 类来完成这一操作。下面是一个用于读取文本文件并返回其全部内容作为字符串的方法:
```csharp
/// <summary>
/// 读取txt数据
/// </summary>
/// <param name="FilePath">txt完整路径</param>
/// <returns>文件中的文本内容</returns>
public string ReadTXT(string FilePath)
{
try
{
using (StreamReader readString = new StreamReader(FilePath, System.Text.Encoding.Default))
{
string myfile;
myfile = readString.ReadToEnd();
return myfile;
}
}
catch (Exception ex)
{
WriteLog("ReadTXT", ex.ToString());
return null;
}
}
```
上述方法通过传入完整的文件路径参数,利用 `StreamReader` 的构造函数打开该位置下的文本文件,并调用 `ReadToEnd()` 方法一次性获取所有文本内容[^1]。
#### 写入 TXT 文件
对于向现有的文本文件中追加新内容的操作,则可借助于 `StreamWriter` 来实现。这里展示了一个简单的例子,展示了如何创建或打开一个文件并向其中添加新的文本行:
```csharp
using (StreamWriter writer = new StreamWriter(filePath, true)) // 'true' 表示追加模式
{
writer.WriteLine("这是要追加的一行文字");
}
```
这段代码片段说明了当设置第二个布尔型参数为 `true` 时,将会启用追加模式;即如果目标文件已经存在,则不会覆盖原有内容而是继续在其末尾处增加新信息[^2]。
阅读全文
相关推荐













