我需要结合两个相对的 Uris,例如../mypath/
和 myimage.png
创建 ../mypath/myimage.png
。它们不是磁盘上文件的路径,因此 Path.Combine
不合适(它们是网页资源的相对路径)。 new Uri
抛出 ArgumentOutOfRangeException
因为基本 uri 是相对的(不是绝对的)。
除了检查尾部斜杠然后自己组合路径之外,我还有其他选择吗?
编辑:
这是一个测试用例,当第一个 url 不包含尾部斜杠时,Path.Combine 将不起作用:
// The first case fails with result "../testpath\resource.png"
[TestCase("../testpath", "resource.png", "../testpath/resource.png")]
[TestCase("../testpath/", "resource.png", "../testpath/resource.png")]
public void TestPathCombine(string path, string resourceName, string expectedResult) {
string result = Path.Combine(path, resourceName);
Assert.AreEqual(expectedResult, result);
}
最佳答案
如果您的第二部分(就像我自己的情况一样)确实是一个没有任何转义的文件名(因此可能包含 url 的无效字符),这是我最终得到的解决方案:
VirtualPathUtility.Combine(
VirtualPathUtility.AppendTrailingSlash(relativeUri),
Uri.EscapeDataString(fileName));
请注意,此解决方案不支持完整的 uri(带有方案、主机、端口):它会抛出带有完整 uri 的异常。 感谢 Manish Pansiniya 的 mentioning System.Web.VirtualPathUtility .
另外,由于我的文件名实际上是部分文件路径(一些文件夹名后接文件名),而不是直接调用System.Uri.EscapeDataString,我调用了以下函数:
/// <summary>
/// Convert a partial file path to a partial url path.
/// </summary>
/// <param name="partialFilePath">The partial file path.</param>
/// <returns>A partial url path.</returns>
public static string ConvertPartialFilePathToPartialUrlPath(
string partialFilePath)
{
if (partialFilePath == null)
return null;
return string.Join("/",
partialFilePath.Split('/', '\\')
.Select(part => Uri.EscapeDataString(part)));
}
(需要对 .Select 使用 System.Linq,对使用的 string.Join 重载使用 fx4。)
关于c# - 结合两个相对的 Uris,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4390697/