views:

131

answers:

3

In my program I need to check that several paths to files are inside system temporary files folder (for example C:\Users\Roman\AppData\Local\Temp). I haven't found any method in System.IO.File, System.IO.Directory and System.IO.Path classes to do so. So I created my own:

public static bool IsSafeToDeleteFileOrDirectory(string path)
{
    try
    {
        string tempPath = Path.GetFullPath(
                    Path.Combine(Path.GetTempPath(), ".\\")
                    );
        string fullPath = Path.GetFullPath(path);
        return fullPath.StartsWith(tempPath) &&
               fullPath.Length > tempPath.Length;
    }
    catch (Exception ex)
    {}

    return false;            
}

But I am not sure if it will always work. Is there any other simple solution besides traversing the folders tree and checking that each child folder exists and its parent folder is TEMP?

A: 

The StartsWith approach will fail to account for this sort of thing:

tempPath is: /tmp/

fullPath is: /tmp/../etc/evil.cnf

You will need to normalize the two paths first, which will resolve anything like ../

thomasrutter
He's doing that already. GetFullPath()
Carlos A. Ibarra
+1  A: 

System.IO.Directory.Exists() can take relative paths as well. I think that should do it for you.

Tomalak
A: 

I believe your code will work even for thomasrutter's example since the paths are resolved by Path.GetFullPath.

Jakob Christensen