c#创建空的txt文件
时间: 2023-12-13 11:33:20 浏览: 76
以下是两种在C#中创建空的txt文件的方法:
1. 使用FileStream和StreamWriter类创建空的txt文件
```csharp
string fileName = "example.txt"; // 文件名
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); // 文件路径,保存到桌面
FileStream fs = System.IO.File.Create(filePath + "\\" + fileName); // 创建文件流
StreamWriter sw = new StreamWriter(fs); // 创建写入流
sw.Write(""); // 写入空字符串
sw.Close(); // 关闭写入流
fs.Close(); // 关闭文件流
```
2. 使用File类的Create方法创建空的txt文件
```csharp
string fileName = "example.txt"; // 文件名
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); // 文件路径,保存到桌面
if (!File.Exists(filePath + "\\" + fileName)) // 判断文件是否存在
{
File.Create(filePath + "\\" + fileName); // 创建空的txt文件
MessageBox.Show("文件创建成功!"); // 弹出提示框
}
```