有没有简单的方法来检查文件的路径是否位于某个文件夹(.NET 框架)内?
在我的程序中,我需要检查系统临时文件文件夹内的多个文件路径(例如C:\Users\Roman\AppData\Local\Temp)。 我没有在 System.IO.File、System.IO.Directory 和 System.IO.Path 类中找到任何方法来执行此操作。 所以我创建了自己的:
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;
}
但我不确定它是否永远有效。 除了遍历文件夹树并检查每个子文件夹是否存在且其父文件夹是否为 TEMP 之外,还有其他简单的解决方案吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
System.IO。 Directory.Exists()
也可以采用相对路径。 我认为这应该适合你。System.IO.Directory.Exists()
can take relative paths as well. I think that should do it for you.我相信您的代码甚至适用于 thomasrutter 的示例,因为路径是由 Path.GetFullPath 解析的。
I believe your code will work even for thomasrutter's example since the paths are resolved by Path.GetFullPath.
StartsWith 方法将无法解决此类问题:
tempPath is: /tmp/
fullPath is: /tmp/../etc/evil.cnf
您需要首先规范化这两个路径,这将解决诸如 .. /
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 ../