代码
using System;
using System.IO;
public class FileCreator
{
public static void CreateFileIfNotExists(string filePath)
{
try
{
// 检查文件是否存在
if (!File.Exists(filePath))
{
// 获取文件所在的目录路径
string directoryPath = Path.GetDirectoryName(filePath);
// 如果目录不存在,则创建目录
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
Console.WriteLine($"目录已创建: {directoryPath}");
}
// 创建文件
using (File.Create(filePath))
{
// File.Create会返回一个FileStream,using语句会自动关闭它
Console.WriteLine($"文件已创建: {filePath}");
}
}
else
{
Console.WriteLine($"文件已存在: {filePath}");
}
}
catch (Exception ex)
{
Console.WriteLine($"操作出错: {ex.Message}");
}
}
// 示例用法
public static void Main(string[] args)
{
// 示例文件路径
string exampleFilePath = @"C:\MyDocuments\Reports\2023\August\report.txt";
// 调用方法
CreateFileIfNotExists(exampleFilePath);
}
}