在ASP.NET之外组合物理路径和虚拟路径

时间:2009-09-23 05:41:40

标签: c# file-io

我想将虚拟文件路径转换为Windows服务中的物理文件路径。

我知道虚拟目录的物理路径是什么,所以我有以下功能,但感觉就像一个软糖:

public static string GetPhysicalPathFromVirtual(string rootPath, string virtualPath)
{
    int trailingSlash = virtualPath.IndexOf('/', 1) + 1;
    int length = virtualPath.Length - trailingSlash;
    string stripped = virtualPath.Substring(trailingSlash, length);
    stripped = stripped.Replace(@"/", @"\");
    return Path.Combine(rootPath, stripped);
}

以下示例:

string test = FileHelper.GetPhysicalPathFromVirtual(@"T:\generateddocuments\output\", @"/virtualroot/folder/myfile.pdf");

返回:T:\ generateddocuments \ output \ folder \ myfile.pdf

有更优雅的方法吗?

1 个答案:

答案 0 :(得分:1)

Uri class可能对您的任务有所帮助。

请注意,在服务中使用相对路径会暴露出巨大的安全漏洞,因此在编码时应该非常防守。

以下是我提出的建议:

public static string GetPhysicalPathFromVirtual(string rootPath, string virtualPath)
{
    const string mandatoryVirtualPrefix = "/virtualroot/";

    if (!virtualPath.StartsWith(mandatoryVirtualPrefix))
        throw new ArgumentOutOfRangeException(virtualPath, string.Format("Virtual '{0}' path must start with mandatory prefix '{1}'", virtualPath, mandatoryVirtualPrefix));

    var relativePath = virtualPath.Substring(mandatoryVirtualPrefix.Length);

    var rootUri = new Uri(rootPath, UriKind.Absolute);
    var relativeUri = new Uri(relativePath, UriKind.Relative);

    var absoluteUri = new Uri(rootUri, relativeUri);

    if (!rootUri.IsBaseOf(absoluteUri))
        throw new ArgumentOutOfRangeException(virtualPath, string.Format("Virtual path '{0}' can't be outside of root '{1}'", virtualPath, rootPath));

    return absoluteUri.LocalPath;
}