Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

c# - Directory.Delete doesn't work. Access denied error but under Windows Explorer it's ok

I have searched the SO but find nothing.

Why this doesn't work?

Directory.Delete(@"E:3{90120000-001A-0000-0000-0000000FF1CE}-C");

Above line will throw exception "Access is denied". I have admin rigths and I can delete the dir with Explorer.

It looks like some forbidden chars? but Windows Explorer can handle it. How can I delete directories with names like that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Thank you all for your input, it helps me in quick find of solution.

As Phil mentioned "Directory.Delete fails if it is, regardless of permissions (see bottom of msdn.microsoft.com/en-us/library/…)"

In addition Unable to remove Read-Only attribute from folder Microsoft says:

You may be unable to remove the Read-Only attribute from a folder using Windows Explorer. In addition, some programs may display error messages when you try to save files to the folder.

Conclusion: always remove all dir,file attributes diffrent then Normal before deleting. So below code solve the problem:

System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(@"E:3{90120000-0021-0000-0000-0000000FF1CE}-C1");

if (dir.Exists)
{
    setAttributesNormal(dir);
    dir.Delete(true);
}

. . .

function setAttributesNormal(DirectoryInfo dir) {
    foreach (var subDir in dir.GetDirectories())
        setAttributesNormal(subDir);
    foreach (var file in dir.GetFiles())
    {
        file.Attributes = FileAttributes.Normal;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...