C# FileStream如何写入字符串
时间: 2023-11-27 13:51:05 浏览: 48
在 C# 中,可以使用 `StreamWriter` 类来向文件中写入字符串。以下是一个示例:
```csharp
using System.IO;
// 创建一个 FileStream 对象
FileStream fileStream = new FileStream("example.txt", FileMode.Append, FileAccess.Write);
// 创建一个 StreamWriter 对象
StreamWriter streamWriter = new StreamWriter(fileStream);
// 写入字符串
string str = "Hello, World!";
streamWriter.WriteLine(str);
// 关闭 StreamWriter 和 FileStream 对象
streamWriter.Close();
fileStream.Close();
```
在上面的示例中,首先创建了一个 `FileStream` 对象,该对象将文件名设置为 "example.txt",并使用 `FileMode.Append` 和 `FileAccess.Write` 来打开文件以进行写入操作。接下来,创建一个 `StreamWriter` 对象,并使用 `WriteLine` 方法将字符串写入文件中。最后,关闭 `StreamWriter` 和 `FileStream` 对象。
注意,在使用 `StreamWriter` 写入文件时,如果文件不存在,则会自动创建文件。如果文件已经存在,则会将新的文本追加到文件的末尾。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)