开发者

"Access to the system path is denied" when using 'System.IO.Directory.Delete'

开发者 https://www.devze.com 2022-12-19 07:59 出处:网络
I\'m using System.IO.Directory.Delete and trying to delete system folders such as \'My Music\', \'My Videos\' etc, but I get errors similar to \"Access to the system path \'C:\\users\\jbloggs\\Saved G

I'm using System.IO.Directory.Delete and trying to delete system folders such as 'My Music', 'My Videos' etc, but I get errors similar to "Access to the system path 'C:\users\jbloggs\Saved Games' is denied". I can however delete these folders via Explorer without any problems, I have full permissions to these folders. Any suggestions on what I can try?

My code:

public static void ClearAttributes(string currentDir)
{
    if (Directory.Exists(currentDir))
  开发者_如何学JAVA  {
        string[] subDirs = Directory.GetDirectories(currentDir);
        foreach (string dir in subDirs)
            ClearAttributes(dir);
        string[] files = files = Directory.GetFiles(currentDir);
        foreach (string file in files)
            File.SetAttributes(file, FileAttributes.Normal);
    }
}

Usage:

try
{
    ClearAttributes(FolderPath);
    System.IO.Directory.Delete("C:\\users\\jbloggs\\Saved Games", true);
}
catch (IOException ex)
{
    MessageBox.Show(ex.Message);
}


Yes, that folder has the "read only" attribute set. This would work:

var dir = new DirectoryInfo(@"c:\temp\test");
dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly;
dir.Delete();

You should always pay attention to the file attributes when you delete stuff. Be sure to stay clear from anything that is System or ReparsePoint. And careful with ReadOnly and Hidden.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号