C# Folder Creation Error Handling | Fix Directory Issues
When creating a folder in C#, if an error occurs, there may be several situations and solutions.
- Create a new folder.
try
{
Directory.CreateDirectory("C:\\path\\to\\folder");
}
catch(UnauthorizedAccessException)
{
Console.WriteLine("没有足够的权限创建文件夹");
}
- Checking if a directory exists
string folderPath = "C:\\path\\to\\folder";
if(!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
else
{
Console.WriteLine("文件夹已存在");
}
- Incorrect path: Providing an inaccurate folder path may result in the failure to create the folder. Please make sure the folder path is correct and use either an absolute or relative path.
string folderPath = "C:\\path\\to\\folder";
// 或者使用相对路径
// string folderPath = ".\\folder";
Directory.CreateDirectory(folderPath);
By examining these issues and addressing them accordingly, you should be able to resolve the errors when creating folders.