无法删除与Directory.Delete目录(路径,真实) [英] Cannot delete directory with Directory.Delete(path, true)

查看:1568
本文介绍了无法删除与Directory.Delete目录(路径,真实)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是.NET 3.5,试图递归删除使用目录:

I'm using .NET 3.5, trying to recursively delete a directory using:

Directory.Delete(myPath, true);

我的理解是,这应该抛出如果文件正在使用中或者有权限问题,但除此之外,它应该删除该目录及其所有内容。

My understanding is that this should throw if files are in use or there is a permissions problem, but otherwise it should delete the directory and all of its contents.

不过,我偶尔会得到这样的:

However, I occasionally get this:

System.IO.IOException: The directory is not empty.
    at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
    at System.IO.Directory.DeleteHelper(String fullPath, String userPath, Boolean recursive)
    at System.IO.Directory.Delete(String fullPath, String userPath, Boolean recursive)
    ...

我并不感到惊讶,该方法有时会抛出,但我很惊讶,当递归是真的得到这个特定的消息。 (我的知道的目录不为空。)

还有一个原因是我想看到这个,而不是AccessViolationException?

Is there a reason I'd see this instead of AccessViolationException?

推荐答案

我就遇到了这个问题之前。

I ran into this problem before.

问题的根源在于,该功能不会删除是目录结构中的文件。那么,你需要做的就是创建一个函数,删除删除目录本身之前那么所有的目录,目录结构中的所有文件。我知道这违背了第二个参数,但它是一个更安全的方法。此外,你可能会想从文件中删除只读访问的属性,你删除他们的权利之前。否则,将引发异常。

The root of the problem is that this function does not delete files that are within the directory structure. So what you'll need to do is create a function that deletes all the files within the directory structure then all the directories before removing the directory itself. I know this goes against the second parameter but it's a much safer approach. In addition, you will probably want to remove READ-ONLY access attributes from the files right before you delete them. Otherwise that will raise an exception.

就在这个耳光code到项目中。

Just slap this code into your project.

public static void DeleteDirectory(string target_dir)
{
    string[] files = Directory.GetFiles(target_dir);
    string[] dirs = Directory.GetDirectories(target_dir);

    foreach (string file in files)
    {
        File.SetAttributes(file, FileAttributes.Normal);
        File.Delete(file);
    }

    foreach (string dir in dirs)
    {
        DeleteDirectory(dir);
    }

    Directory.Delete(target_dir, false);
}

另外,对我来说,我个人的机器被允许是因为删除你希望有人呼吁 C中,它的功能区增加一个限制:\ WINDOWS(%WINDIR%) C:\

这篇关于无法删除与Directory.Delete目录(路径,真实)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆