HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Deleting folders is a risky business

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
businessdeletingriskyfolders

Problem

Deleting folders 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!)

/// 
/// carefully remove directory and its files
/// verify the directory is located under the %temp%
/// and it is not e.g. C:\
/// 
///         
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 systemDirs = new List
{
Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles),
Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFilesX86),
Environment.GetFolderPath(Envi

Solution

When all you have is a hammer, every problem looks like a nail.

You're trying to do something with code, that's not the code's job. Delete all this code and tackle the problem at the root: make sure your code runs with the appropriate permissions.

It's that simple.

-- My humble opinion

Deleting folders is a risky business

Indeed! If your running code doesn't have permission to wipe out your hard drive, you have some exceptions to deal with, i.e. you should wrap I/O calls in a try...catch block.

Context

StackExchange Code Review Q#8332, answer score: 8

Revisions (0)

No revisions yet.