c# - 如何删除包含文件的文件夹?

标签 c#

我想从我的程序中删除包含或不包含文件/文件夹的文件夹。

代码:

    static void Main(string[] args)
    {
        List<string> foldersToDelete = new List<string>();

        foreach(var f in System.IO.Directory.GetDirectories(@"C:\Users\Public\MySpecialTempFolder"))
        {
            var dir = new DirectoryInfo(f);
            dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly;

            long size = GetDirectorySize(f);

            // delete folders less then 1 mb
            if (size < 1000000)
                foldersToDelete.Add(f);
        }

        foreach (var s in foldersToDelete)
            System.IO.Directory.Delete(s, true);
    }

    private static long GetDirectorySize(string folderPath)
    {
        DirectoryInfo di = new DirectoryInfo(folderPath);
        return di.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(fi => fi.Length);
    }

但是...当我运行它时,我得到拒绝访问。怎么了,我可以通过右键单击文件夹并在那里删除它然后手动执行此操作

最佳答案

尝试使用 Visual Basic 删除:

var directory = new DirectoryInfo(targetDir);
if (directory.Exists)
{
    Microsoft.VisualBasic.FileIO.FileSystem.DeleteDirectory(targetDir, Microsoft.VisualBasic.FileIO.DeleteDirectoryOption.DeleteAllContents);
}

来自 File.Delete Access to the path is denied

关于c# - 如何删除包含文件的文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32998453/

相关文章:

c# - 对不需要实例的扩展方法进行空检查?

c# - 使用 msmq 进行异步日志记录

c# - 在模型中声明列表

c# - 如何使用 Moq 创建带有 JSON 正文的模拟 HTTP 发布请求

c# - 通过服务帐户使用 Google SpreadsheetsService

c# - 该类型不能用作泛型类型或方法 'T' 中的类型参数 'BaseController<T>' 。没有隐式引用

c# - 归并排序问题

c# - 使用 ini/appconfig 文件或 sql server 文件来存储用户配置?

c# - 将 UInt32 转换为 Int32 : Different compiler results

c# - 如何等待所有异步操作?