如何在C#中读取和写入一个文本文件?

在C#中,可以使用`System.IO`命名空间下的各种类来处理文件的读取和写入操作。这里以读取和写入文本文件为例。

读取文本文件可以使用`StreamReader`类或`File.ReadAllText`方法。以下是使用`StreamReader`读取文件的示例代码:

```csharp
using System;
using System.IO;

class Program
{
static void Main()
{
string path = "example.txt";

try
{
using (StreamReader sr = new StreamReader(path))
{
string line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
Console.WriteLine("读取文件出错: " + e.Message);
}
}
}
```

写入文本文件可以使用`StreamWriter`类或`File.WriteAllText`方法。以下是使用`StreamWriter`写入文件的示例代码:

```csharp
using System;
using System.IO;

class Program
{
static void Main()
{
string path = "example.txt";

try
{
using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine("这是写入文件的第一行文本。");
sw.WriteLine("这是写入文件的第二行文本。");
}
}
catch (Exception e)
{
Console.WriteLine("写入文件出错: " + e.Message);
}
}
}
```

在这段代码中,`StreamReader`和`StreamWriter`都支持 `using` 语句来确保在使用完成后释放资源,这是一种推荐的用法,因为它可以有效防止文件锁定或资源泄漏的问题。使用`try-catch`块可以捕获文件操作中的异常,便于调试和错误处理。

若文章对您有帮助,帮忙点个赞!

0
0
发布时间 2025-03-13 16:00:13
0 条回复(回复会通过微信通知作者)
点击加载更多评论
登录 后再进行评论
(微信扫码即可登录,无需注册)