C# 读取和写入txt文件
时间: 2024-09-26 10:08:01 浏览: 28
C# 读取和写入INI配置文件
在C#中,读取和写入文本文件(txt或其他纯文本文件)非常直观,可以使用`StreamReader`和`StreamWriter`这两个内置类。以下是基本步骤:
**读取txt文件:**
```csharp
using System.IO;
string filePath = "path_to_your_file.txt"; // 替换为你的文件路径
try
{
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line); // 打印每一行内容
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error reading file: {ex.Message}");
}
```
**写入txt文件:**
```csharp
using System.IO;
string filePath = "path_to_your_file.txt"; // 替换为你要写入的文件路径
string contentToWrite = "This is some text to write into the file.\n";
try
{
using (StreamWriter writer = new StreamWriter(filePath, true)) // 如果文件已存在,追加内容;如果不存在,创建新文件
{
writer.WriteLine(contentToWrite);
}
Console.WriteLine("Content written successfully.");
}
catch (Exception ex)
{
Console.WriteLine($"Error writing to file: {ex.Message}");
}
```
阅读全文