温馨提示×

c# directory如何清空目录

c#
小樊
89
2024-11-20 17:13:56
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C#中,你可以使用System.IO命名空间中的Directory类来清空目录。以下是一个示例代码,展示了如何清空一个目录及其所有子目录和文件:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string directoryPath = @"C:\path\to\your\directory";

        try
        {
            // 清空目录
            Directory.Delete(directoryPath, true);
            Console.WriteLine("目录已成功清空。");
        }
        catch (Exception ex)
        {
            Console.WriteLine("清空目录时发生错误: " + ex.Message);
        }
    }
}

在这个示例中,Directory.Delete方法用于删除指定的目录及其所有子目录和文件。第二个参数true表示递归删除目录及其内容。如果目录为空,Directory.Delete方法将直接删除目录。如果在删除过程中发生任何错误,将抛出异常,你可以在catch块中处理这些异常。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:c# directory能删除空目录吗

0