Sunday, April 3, 2011

Is there any simple way to check that a path to a file is inside a certain folder (.NET framework)?

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?

From stackoverflow
  • 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 ../

    Carlos A. Ibarra : He's doing that already. GetFullPath()
  • System.IO.Directory.Exists() can take relative paths as well. I think that should do it for you.

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

0 comments:

Post a Comment