C#: Delete folder, including its sub-folders and files, even if marked as ‘read-only’

The Directory class, which is in the namespace System.IO, has a method called Delete with two overloads, in which one of them gets the name of the folder to be deleted and a boolean value to indicate if the method should run recursively and remove all sub-folders and files as well:

// Delete the folder 'c:\Projects' and all of its content
Directory.Delete(@"c:\Projects", true);

The code above should be enough, however, we get an exception of the type UnauthorizedAccessException if we there is one or more files marked as read-only inside the folder or any of the sub-folders:

System.UnauthorizedAccessException: Access to the path 'Readme.txt' is denied.
   at System.IO.Directory.DeleteHelper(String fullPath, String userPath, Boolean recursive)
   at System.IO.Directory.Delete(String fullPath, String userPath, Boolean recursive)
   at System.IO.Directory.Delete(String path, Boolean recursive)

The solution to this problem is to stop using the method Directory.Delete, and implement a custom method, recursive, that deletes all files and sub-folders, checking for (and removing) the read-only attribute before deleting each file. Something like this:

public static void DeleteDirectory(string path)
{
    DeleteDirectory(path, false);
}

public static void DeleteDirectory(string path, bool recursive)
{
    // Delete all files and sub-folders?
    if (recursive)
    {
        // Yep... Let's do this
        var subfolders = Directory.GetDirectories(path);
        foreach (var s in subfolders)
        {
            DeleteDirectory(s, recursive);
        }
    }

    // Get all files of the folder
    var files = Directory.GetFiles(path);
    foreach (var f in files)
    {
        // Get the attributes of the file
        var attr = File.GetAttributes(f);

        // Is this file marked as 'read-only'?
        if ((attr & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
        {
            // Yes... Remove the 'read-only' attribute, then
            File.SetAttributes(f, attr ^ FileAttributes.ReadOnly);
        }

        // Delete the file
        File.Delete(f);
    }

    // When we get here, all the files of the folder were
    // already deleted, so we just delete the empty folder
    Directory.Delete(path);
}

And now, to delete folders content, including ‘read-only’ files, we just have to use this new method:

// Delete all files from the folder 'c:\Games', but
// keep all sub-folders and its files
DeleteDirectory(@"c:\Games");

// Delete the folder 'c:\Projects' and all of its content
DeleteDirectory(@"c:\Projects", true);

// Delete all files from the folder 'c:\Software', but
// keep all sub-folders and its files
DeleteDirectory(@"c:\Software", false);
This entry was posted in .NET and tagged , , , , . Bookmark the permalink.

5 Responses to C#: Delete folder, including its sub-folders and files, even if marked as ‘read-only’

  1. Papria says:

    Very good article, thanks.

  2. Joe DeJohn says:

    Very helpful. Thank-you.

  3. SARAN says:

    very useful and simplified Thank you

  4. sbg says:

    thanks but i get an error :
    {“Could not find a part of the path ‘C:\\Users\\sbg\\Documents\\Visual Studio 2012\\Projects\\projTest\\projTest\\bin\\Debug\\System.Linq.Enumerable+WhereArrayIterator`1[System.String]‘.”}

    and the debugger points to this line:
    // Yep… Let’s do this
    var subfolders = Directory.GetDirectories(path);

  5. nera says:

    Very cool, thanks! Works perfectly! Exactly what I was looking for!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>