8

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))
    {
        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);
}
Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
James T
  • 83
  • 1
  • 1
  • 4
  • 1
    There are no relevant google matches to the exact string "Access to the system path". Is this the exact wording of the error message? – Robert Harvey Feb 01 '10 at 21:06
  • Try quoting your path string. Use @"C:\users\jbloggs\Saved Games". ALso, show `ex.ToString()`. Finally, this is related to .NET, not to the C# programming language. – John Saunders Feb 01 '10 at 21:07
  • Attributes aren't always the issue. Another cause is that some application has that directory or something under it open. In my case, the application was Windows Explorer! It had the relevant directory locked, even though the "current" folder was outside the one I was trying to rename. My application could not rename the directory until I closed Explorer. – Keith Robertson Nov 28 '13 at 00:33

1 Answers1

16

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.

Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536