c# - 如何确保所有写入的文件都在给定路径下(防止目录访问)

标签 c# directory parent

我们有一个 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/

相关文章:

version-control - 如何在 Team Foundation Server 中一次隐藏多个文件夹?

bash - 我怎样才能得到父脚本的名字?

c# - 从 WebBrowser 控件向父应用程序发送消息

c# - Visual Studio 2015 无法识别引用

c# - 是否可以将相同的 DLL 添加两次到 AppDomain 中,或者最好重新使用加载的 DLLC?

c++ - 如何使用 C++ 创建一个对 "everyone"具有共享访问权限的文件夹

ios - 为什么 swift 无法识别我的资源?

c# - 创建新类或结构时 .NET 中的内存使用情况

java - 从子线程访问父实例

javascript - 从父窗口的新选项卡中的弹出窗口打开链接