Click here to Skip to main content
Click here to Skip to main content

Deleting folders is a risky business

By , 30 Jan 2012
 
Deleting folder programmatically is extremely dangerous. It is enough for somebody else to change a configuration file or constant variable including the target folder's name to, say C:\, and that's it: the workstation is paralyzed!
 
Following suggested methods are to prevent such a situation. Their aim is to wrap the low level, possibly recursive file system operation with the necessary validation and clear facade - look twice, delete once.
 

Delete temporary directory created by current user (non recursive!)

 
    /// <summary>
    /// carefully remove directory and its files
    /// verify the directory is located under the %temp%
    /// and it is not e.g. C:\
    /// </summary>
    /// <param name="dir"></param>

    public static void DeleteTempDirShallow(string dir)
    {
        // check if it is an invalid directory path,
        // e.g. a disk drive or just a bad string

        if (! Directory.Exists(dir)) return;
 
        DirectoryInfo userTempDirInfo = new DirectoryInfo(Path.GetTempPath());
        DirectoryInfo dirInfo = new DirectoryInfo(dir);
 
        if (dirInfo.FullName.Contains(userTempDirInfo.FullName))
        {
            foreach (FileInfo file in dirInfo.GetFiles())
                file.Delete();
 
            dirInfo.Delete(); // just clean up the empty dir
        }
    }
 

Delete temporary directory created by current user (recursive!)

 
    public static void DeleteTempDirRecursive(string dir)
    {
        // check if it is an invalid directory path,
        // e.g. a disk drive or just a bad string
        if (! Directory.Exists(dir)) return;
 
        DirectoryInfo userTempDirInfo = new DirectoryInfo(Path.GetTempPath());
        DirectoryInfo dirInfo = new DirectoryInfo(dir);
 
        if (dirInfo.FullName.Contains(userTempDirInfo.FullName))
        {
            dirInfo.Delete(recursive: true);
        }
    }
 

Do I try to delete any root or system folder?

 
    static List<string> systemDirs = new List<string>
    {
        Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles),
        Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFilesX86),
        Environment.GetFolderPath(Environment.SpecialFolder.CommonPrograms),
        Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu),
        Environment.GetFolderPath(Environment.SpecialFolder.CommonStartup),
        Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
        Environment.GetFolderPath(Environment.SpecialFolder.NetworkShortcuts),
        Environment.GetFolderPath(Environment.SpecialFolder.PrinterShortcuts),
        Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
        Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
        Environment.GetFolderPath(Environment.SpecialFolder.Resources),
        Environment.GetFolderPath(Environment.SpecialFolder.StartMenu),
        Environment.GetFolderPath(Environment.SpecialFolder.Startup),
        Environment.GetFolderPath(Environment.SpecialFolder.System),
        Environment.GetFolderPath(Environment.SpecialFolder.SystemX86),
        Environment.GetFolderPath(Environment.SpecialFolder.Templates),
        Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
        Environment.GetFolderPath(Environment.SpecialFolder.Windows),
    };
 
    /// <summary>
    /// check if the argument dir is a disk drive,
    /// is a system (sub-)folder
    /// and should not be erased
    /// </summary>
    /// <param name="dir"></param>
    /// <returns></returns>
    public static bool IsSystemOrRootDir(string dir)
    {
        // check if it is an invalid directory path,
        // or just a bad string
        if (! Directory.Exists(dir)) return true;
 
        DirectoryInfo dirInfo = new DirectoryInfo(dir);
 
        // is it a root (disk drive)? 
        if (dirInfo.Parent == null) return true;
 
        bool result = false;
        systemDirs.ForEach(sysDir => { result = result ||
                                       dirInfo.FullName.Contains(sysDir); } );
        return result;
    }
 

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Michael Gr
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5 Pinmemberhypermellow11 Feb '13 - 22:53 
GeneralMy vote of 4 Pinmemberjfriedman13 May '12 - 3:57 
GeneralRe: Thank You! PinmemberMichael Gr30 Jan '12 - 2:10 
GeneralRe: OK , I updated my Vote, +5 PinmemberRajesh Anuhya30 Jan '12 - 1:55 
Generalnice !! PinmemberAbhishek Unnikrishnan12 Feb '12 - 5:45 
GeneralReason for my vote of 5 I wasn't aware of this in 24 years o... Pinmemberjavaevangelist7 Feb '12 - 8:18 
GeneralReason for my vote of 5 Very nice PinmemberTigerHajtos6 Feb '12 - 21:24 
GeneralReason for my vote of 5 I have to admit, I have never (thank... PinmemberMarek Roszak6 Feb '12 - 20:55 
GeneralNever thought about this.. Thankyou. Have 5 PinmemberPankaj Chamria30 Jan '12 - 2:55 
GeneralRe: Thanks Pankaj. PinmemberMichael Gr30 Jan '12 - 22:34 
GeneralCopied from Here:http://codereview.stackexchange.com/questio... PinmemberRajesh Anuhya30 Jan '12 - 1:18 
GeneralReason for my vote of 1 Copied from Here : http://codereview... PinmemberRajesh Anuhya30 Jan '12 - 1:18 
GeneralRe: Dear Rajesh. Actually I have published the article first at ... Pinmemberquiet.step30 Jan '12 - 1:38 
GeneralReason for my vote of 5 Very nice! PinmemberPablo Aliskevicius29 Jan '12 - 19:35 
GeneralRe: Thanks. PinmemberMichael Gr30 Jan '12 - 2:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 30 Jan 2012
Article Copyright 2012 by Michael Gr
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid