c#读写text文件
时间: 2023-08-04 18:02:24 浏览: 80
你可以使用C#中的`System.IO`命名空间中的`StreamReader`和`StreamWriter`类来读写文本文件。下面是一个示例,演示如何使用这两个类进行文件读写操作:
```csharp
using System;
using System.IO;
class Program
{
static void Main()
{
// 写入文本文件
string file = "example.txt";
string content = "Hello, World!";
using (StreamWriter writer = new StreamWriter(file))
{
writer.WriteLine(content);
}
Console.WriteLine("文本文件已写入成功。");
// 读取文本文件
using (StreamReader reader = new StreamReader(file))
{
string line = reader.ReadLine();
Console.WriteLine("读取的内容: " + line);
}
}
}
```
在上面的示例中,首先我们使用`StreamWriter`类创建一个名为`example.txt`的文本文件,并将字符串`Hello, World!`写入文件中。然后,使用`StreamReader`类读取文件的内容,并将其输出到控制台。
请注意,我们使用了`using`语句来自动处理文件流的打开和关闭,以确保资源正确释放。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)