C#++将字符串保存入一个新建txt
时间: 2024-06-13 08:09:21 浏览: 18
以下是C#将字符串保存到新建txt文件的代码示例:
```csharp
using System;
using System.IO;
using System.Text;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
string txtPath = @"1.txt";
string str = "祸莫大于不知足,咎莫大于欲得.";
using (FileStream fs = new FileStream(txtPath, FileMode.Create, FileAccess.Write))
{
byte[] buffer = Encoding.UTF8.GetBytes(str);
fs.Write(buffer, 0, buffer.Length);
}
Console.ReadKey();
}
}
}
```
在上述代码中,我们使用了`FileStream`类来创建一个新的txt文件,并将字符串写入该文件中。`FileMode.Create`参数表示如果文件不存在,则创建该文件;如果文件已存在,则覆盖该文件。`FileAccess.Write`参数表示我们要对该文件进行写操作。`Encoding.UTF8.GetBytes()`方法将字符串转换为字节数组,然后使用`fs.Write()`方法将字节数组写入文件中。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)