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?