【问题标题】:How to ensure all files written are below a given path (prevent directory access)如何确保写入的所有文件都低于给定路径(防止目录访问)
【发布时间】:2011-10-18 20:12:02
【问题描述】:

我们有一个 C# 应用程序,它将文件写入一个可配置的位置。文件集(和相对路径)在运行时确定。

我们要确保它不能在配置的位置之外写入文件。

例如,配置的位置可能是c:\Stuff\Export,程序在C:\Stuff\Important下写任何东西都会出错

真的,我认为我们可以通过两种方式实现这一目标: 1)断言没有任何相对路径(要写入的文件)指定“父目录”(通常是“../”) - System.Path 没有指定“父目录”路径组件(就像它用于路径分隔一样即 System.Path.PathSeparator)。我觉得在字符串中检查“../”有点笨拙。

2) 断言生成的所有最终绝对路径(通过将输出位置与文件相对路径相结合)相对于输出位置,即在输出位置下方。不过,我不确定该怎么做。

Example usage:
Output directory: c:\Stuff\Export
Output path 1: "foo\bar\important.xls"
Output path 2: "foo\boo\something.csv"
Output path 3: "../../io.sys"

Expected final files
1. c:\Stuff\Export\foo\bar\important.xls
2. c:\Stuff\Export\foo\boo\something.csv
3. Should throw exception

【问题讨论】:

标签: c# directory parent


【解决方案1】:

如果您在两个路径上创建 DirectoryInfo 实例,则其 FullName 属性应返回完全限定的规范路径。因此,如果您只是对要比较的双方都这样做,则可以这样做:

if (chosenDirectory.FullName != configuredDirectory.FullName)
{
    throw new InvalidOperationException(
        String.Format("Invalid path {0}.", chosenDirectory));
}

由于FullName 只是一个字符串,您可以对路径进行常规字符串比较,例如:

if (!chosenDirectory.FullName.StartsWith(configuredDirectory.FullName,
    StringComparison.InvariantCultureIgnoreCase))
{
    throw new InvalidOperationException(
        String.Format("Invalid path {0}.", chosenDirectory));
}

如果您不想在配置的目录中允许子目录,您也可以使用Parent 属性并将其FullName 与所选目录进行比较:

if (!chosenDirectory.Parent.FullName.Equals(configuredDirectory.FullName,
    StringComparison.InvariantCultureIgnoreCase))
{
    throw new InvalidOperationException(
        String.Format("Invalid path {0}.", chosenDirectory));
}

【讨论】:

    【解决方案2】:

    这里有一个快速的解决方案:

    string chroot = @"C:\root\child";
    string requestedPath = @"..\";
    string path = Path.GetFullPath(Path.Combine(chroot, requestedPath));
    if (!path.StartsWith(chroot, StringComparison.Ordinal))
        throw new Exception("Oops, caught ya!");
    

    编辑: 如果您想知道给定路径是否为有效目录:Directory.Exists(path)

    【讨论】:

      猜你喜欢
      • 2010-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-22
      • 2012-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多