ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

DeleteWithPrejudice and Purge

These 2 extension method allows you to delete a folder or just purge all the folder content even if there are Readonly, System, and/or Hidden attributes files in it. The default Delete method doesn't work if there are files with Readonly, System, and/or Hidden attributes.

Source

public static void DeleteWithPrejudice(this DirectoryInfo directoryInfo)
{
    directoryInfo.DeleteWithPrejudice(true);
}

public static void Purge(this DirectoryInfo directoryInfo)
{
    directoryInfo.DeleteWithPrejudice(false);
}

private static void DeleteWithPrejudice(this DirectoryInfo directoryInfo, bool deleteRoot)
{

    /* Determine whether the directory exists */
    if (!directoryInfo.RefreshExists())
    {
        return;
    }
    directoryInfo.Refresh();
    /* Remove Readonly, System, and Hidden attributes prior to deletion */
    directoryInfo.Attributes = FileAttributes.Directory;

    directoryInfo.DeleteAllFiles(true);

    var folderPaths = new List<DirectoryInfo>();

    foreach (var subDirectory in directoryInfo.GetDirectories("*", SearchOption.AllDirectories))
    {
        folderPaths.Add(subDirectory);
    }
    if (deleteRoot)
    {
        folderPaths.Add(directoryInfo);
    }

    // sort has a side effect that means the deepest directories will be at the top
    folderPaths.Sort((x, y) => y.FullName.CompareTo(x.FullName));

    foreach (var folderPath in folderPaths)
    {
        if (!folderPath.RefreshExists())
        {
            continue;
        }
        folderPath.Attributes = directoryInfo.Attributes & ~ReadOnlyHiddenSystemFileAttributes;
        folderPath.Refresh();
        folderPath.Delete();
    }
}

Example

directoryToDelete.DeleteWithPrejudice();

Author: John Simons

Submitted on: 17 jun. 2010

Language: C#

Type: System.IO.DirectoryInfo

Views: 4572