65.9K
CodeProject is changing. Read more.
Home

Deleting protected folders in Windows 7

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.82/5 (13 votes)

Mar 22, 2011

CPOL
viewsIcon

32709

Deleting protected folders in Windows 7

I had trouble lately trying to get rid of a lot of folders from a previous windows installation. I had d:\temp\windows d:\temp\program files ... This had to do with ownership and access rights. Running this program did the trick. Perhaps someone will want to push it a bit further and make a real utility of it. USE AT YOUR OWN RISKS, THIS PROGRAM IS LETHAL FOR YOUR HARD DISKS
class Program
{
    static void Main(string[] args)
    {
        var path = args[0];
        DeleteFolder(new System.IO.DirectoryInfo(path));
    }

    private static void DeleteFolder(DirectoryInfo directoryInfo)
    {
        GrantAccess(directoryInfo.FullName);
        try
        {
            foreach (DirectoryInfo d in directoryInfo.GetDirectories())
            {
                DeleteFolder(d);
            }
        }
        catch { }

        try
        {
            foreach (FileInfo f in directoryInfo.GetFiles())
            {
                GrantAccess(f.FullName);
                try
                {
                    f.Delete();
                    Console.WriteLine("Deleted File {0}", f.FullName);
                }
                catch { }
            }
        }
        catch { }

        try
        {
            directoryInfo.Delete(true);
            Console.WriteLine("Deleted Folder {0}", directoryInfo.FullName);
        }
        catch { }

    }

    private static void GrantAccess(string filepath)
    {

        var fs = File.GetAccessControl(filepath);
        var sid = fs.GetOwner(typeof(SecurityIdentifier));
        var ntAccount = new NTAccount(Environment.UserDomainName, Environment.UserName);
        try
        {
            var currentRules = fs.GetAccessRules(true, false,typeof(NTAccount));
            foreach (var r in currentRules.OfType<FileSystemAccessRule>())
            {
                Console.WriteLine(r.AccessControlType + " " + r.FileSystemRights);
            }
            var newRule = new FileSystemAccessRule(
                ntAccount, FileSystemRights.FullControl,
                AccessControlType.Allow);
            fs.AddAccessRule(newRule);
            File.SetAccessControl(filepath, fs);
        }
        catch { }
        finally { fs=null; sid=null; ntAccount=null;} 
    }
}
----------------------- I would recommend to add the finally{fs=null; sid=null; ntAccount=null;} to the function in order to ensure that the objects obtained such powerful control over file system will be disposed/finalized as soon as possible in any scenario. (added by Alex Bell)