c#创建和删除文件夹
时间: 2024-11-12 08:31:24 浏览: 11
在C#中,你可以使用`System.IO`命名空间下的几个类和方法来操作文件和文件夹。下面是创建和删除文件夹的基本步骤:
**创建文件夹:**
```csharp
using System.IO;
// 创建路径字符串
string folderPath = @"C:\path\to\new_folder";
try
{
// 使用Directory.CreateDirectory()方法创建新文件夹
Directory.CreateDirectory(folderPath);
Console.WriteLine($"Folder '{folderPath}' created successfully.");
}
catch (IOException e)
{
Console.WriteLine($"Failed to create folder: {e.Message}");
}
```
**删除文件夹:**
```csharp
using System.IO;
using System.Security.AccessControl; // 需要此命名空间来处理权限
// 删除路径字符串,如果存在则删除
string folderPath = @"C:\path\to\delete_folder";
if (Directory.Exists(folderPath))
{
try
{
// 使用Directory.Delete()方法删除文件夹,设置recursive参数为true以递归删除包含的所有子文件夹和文件
bool success = Directory.Delete(folderPath, true);
if (success)
{
Console.WriteLine($"Folder '{folderPath}' deleted successfully.");
}
else
{
Console.WriteLine($"Failed to delete folder: Access denied or not empty.");
}
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine($"Permission denied: {e.Message}");
}
catch (DirectoryNotFoundException e)
{
Console.WriteLine($"Folder not found: {e.Message}");
}
}
else
{
Console.WriteLine($"Folder '{folderPath}' does not exist.");
}
```
记得在实际操作中处理异常,特别是权限相关的异常。
阅读全文