C# 自动创建 TXT 文件:文件夹不存在就创建
您可以使用'System.IO'命名空间中的'File'和'Directory'类来创建文件和文件夹。以下是一个示例代码,可以在C#中创建txt文件时自动创建文件夹:
using System;
using System.IO;
class Program
{
static void Main()
{
string folderPath = @"C:\YourFolderPath";
string filePath = Path.Combine(folderPath, "YourFileName.txt");
// 检查文件夹是否存在,如果不存在则创建
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
// 检查文件是否存在,如果不存在则创建
if (!File.Exists(filePath))
{
File.Create(filePath).Close();
}
Console.WriteLine("文件创建成功!");
}
}
在上面的示例中,您需要将'YourFolderPath'更改为要创建文件夹的路径,并将'YourFileName.txt'更改为要创建的文件名。如果文件夹不存在,'Directory.CreateDirectory'方法将创建文件夹。如果文件不存在,'File.Create'方法将创建文件,并使用'Close'方法关闭文件流。
请注意,'Create'方法在创建文件后会返回一个'FileStream'对象,如果不关闭该流,其他进程可能无法访问该文件。因此,我们在这里使用'Close'方法来关闭文件流。
希望这可以帮助到您!
原文地址: https://www.cveoy.top/t/topic/qvhK 著作权归作者所有。请勿转载和采集!