Click here to Skip to main content
12,635,428 members (24,685 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

25.2K views
18 bookmarked
Posted

Deleting Folders is a Risky Business

, 14 Oct 2016 CPOL
Rate this:
Please Sign up or sign in to vote.
Deleting folder programmatically is extremely dangerous. It can erase your system.

Introduction

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!

The 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;
 
    // is it a system (sub-)folder?
    return systemDirs.Any(
                 sysDir => dirInfo.FullName
                           .IndexOf(sysDir, StringComparison.OrdinalIgnoreCase) >= 0);
}

References

License

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

Share

About the Author

Michael Gr
President Triple C Computation Ltd.
United States United States
No Biography provided

You may also be interested in...

Pro
Pro

Comments and Discussions

 
QuestionPlacing too much faith in Path.GetTempPath() Pin
dandy7217-Oct-16 12:06
memberdandy7217-Oct-16 12:06 
AnswerRe: Placing too much faith in Path.GetTempPath() Pin
Michael Gr18-Oct-16 9:26
memberMichael Gr18-Oct-16 9:26 
GeneralRe: Placing too much faith in Path.GetTempPath() Pin
dandy7218-Oct-16 10:45
memberdandy7218-Oct-16 10:45 
Question[My vote of 1] gg Pin
maxoptimus17-Oct-16 0:30
membermaxoptimus17-Oct-16 0:30 
AnswerRe: [My vote of 1] gg Pin
Michael Gr17-Oct-16 9:48
memberMichael Gr17-Oct-16 9:48 
GeneralRe: [My vote of 1] gg Pin
maxoptimus18-Oct-16 0:40
membermaxoptimus18-Oct-16 0:40 
GeneralRe: [My vote of 1] gg Pin
Michael Gr18-Oct-16 9:31
memberMichael Gr18-Oct-16 9:31 
GeneralRe: [My vote of 1] gg Pin
dandy7218-Oct-16 10:49
memberdandy7218-Oct-16 10:49 
GeneralRe: [My vote of 1] gg Pin
maxoptimus18-Oct-16 23:35
membermaxoptimus18-Oct-16 23:35 
Questionlol Pin
Member 1048548716-Oct-16 7:31
memberMember 1048548716-Oct-16 7:31 
AnswerRe: lol Pin
Michael Gr16-Oct-16 11:52
memberMichael Gr16-Oct-16 11:52 
GeneralMy vote of 5 Pin
hypermellow11-Feb-13 23:53
memberhypermellow11-Feb-13 23:53 
GeneralMy vote of 4 Pin
jfriedman13-May-12 4:57
memberjfriedman13-May-12 4:57 
GeneralRe: My vote of 4 Pin
DelphiCoder31-Aug-14 13:36
memberDelphiCoder31-Aug-14 13:36 
GeneralRe: Thank You! Pin
Michael Gr30-Jan-12 3:10
memberMichael Gr30-Jan-12 3:10 
GeneralRe: OK , I updated my Vote, +5 Pin
Rajesh Anuhya30-Jan-12 2:55
memberRajesh Anuhya30-Jan-12 2:55 
Generalnice !! Pin
Abhishek Unnikrishnan12-Feb-12 6:45
memberAbhishek Unnikrishnan12-Feb-12 6:45 
GeneralReason for my vote of 5 I wasn't aware of this in 24 years o... Pin
javaevangelist7-Feb-12 9:18
memberjavaevangelist7-Feb-12 9:18 
GeneralRe: Reason for my vote of 5I wasn't aware of this in 24 years o... Pin
Michael Gr18-Oct-16 9:37
memberMichael Gr18-Oct-16 9:37 
GeneralReason for my vote of 5 Very nice Pin
TigerHajtos6-Feb-12 22:24
memberTigerHajtos6-Feb-12 22:24 
GeneralReason for my vote of 5 I have to admit, I have never (thank... Pin
Marek Roszak6-Feb-12 21:55
memberMarek Roszak6-Feb-12 21:55 
GeneralNever thought about this.. Thankyou. Have 5 Pin
Pankaj Chamria30-Jan-12 3:55
memberPankaj Chamria30-Jan-12 3:55 
GeneralRe: Thanks Pankaj. Pin
Michael Gr30-Jan-12 23:34
memberMichael Gr30-Jan-12 23:34 
GeneralCopied from Here:http://codereview.stackexchange.com/questio... Pin
Rajesh Anuhya30-Jan-12 2:18
memberRajesh Anuhya30-Jan-12 2:18 
GeneralReason for my vote of 1 Copied from Here : http://codereview... Pin
Rajesh Anuhya30-Jan-12 2:18
memberRajesh Anuhya30-Jan-12 2:18 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.161208.2 | Last Updated 15 Oct 2016
Article Copyright 2012 by Michael Gr
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid