Create Folder & Write File in C#: Guide
In C#, you can create a folder using the Directory.CreateDirectory() method and write data to a file using the File.WriteAllText() method. Here is an example code:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string folderPath = @"C:\MyFolder"; // 文件夹路径
string fileName = "myfile.txt"; // 文件名
string filePath = Path.Combine(folderPath, fileName); // 文件完整路径
// 创建文件夹
Directory.CreateDirectory(folderPath);
// 写入数据到文件
string data = "Hello, World!";
File.WriteAllText(filePath, data);
Console.WriteLine("文件夹和文件创建成功,并写入数据成功。");
}
}
In the above example, we start by specifying the folder’s path and file name. Then, we create the folder using the Directory.CreateDirectory() method. Next, we combine the folder path and file name together into a complete file path using the Path.Combine() method. Finally, we write the data into the file using the File.WriteAllText() method.
Please note that if a folder already exists, the Directory.CreateDirectory() method will not throw an error. If a file already exists, the File.WriteAllText() method will overwrite the existing file content.
I hope this is helpful to you!