我们有一个 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
最佳答案
如果您创建一个 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));
}
关于c# - 如何确保所有写入的文件都在给定路径下(防止目录访问),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7813092/