有没有简单的方法来检查文件的路径是否位于某个文件夹(.NET 框架)内?

发布于 2024-07-14 01:33:16 字数 711 浏览 3 评论 0原文

在我的程序中,我需要检查系统临时文件文件夹内的多个文件路径(例如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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

夏末的微笑 2024-07-21 01:33:16

System.IO。 Directory.Exists() 也可以采用相对路径。 我认为这应该适合你。

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

荆棘i 2024-07-21 01:33:16

我相信您的代码甚至适用于 thomasrutter 的示例,因为路径是由 Path.GetFullPath 解析的。

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

新雨望断虹 2024-07-21 01:33:16

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 ../

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文