所以这是我的问题: 我想结合一个 URI 和一个字符串。 URI 是(父)文件夹的路径,而字符串表示子文件夹的路径(不要问我为什么要这样做,这两种类型都需要保持这种方式才能使程序的其余部分正常运行) .
我的代码:
private Uri BuildUri(Uri basePath, string resource)
{
var uriBuilder = new UriBuilder(basePath)
{
Path = resource,
};
return uriBuilder.Uri;
}
如果我用 basePath
调用此代码,例如“D:\Test”和资源是“位置”,URI 构建器将我将这两个组合到 file:///locations 并完全忽略了完整的基本路径。我可能会补充说 basePath
始终是 UriKing.Absolute
我做错了什么?如果我这样做:
var completePath = Path.Combine(basePath.AbsolutePath, resource);
return new Uri(completePath);
它正确地返回了一个 URI,但是由于 Path.Combine 在 Live 环境中有一些问题(即权限),我想使用 UriBuilder(它似乎是为我希望它执行的任务而构建的)。
最佳答案
What am I doing wrong?
您正在组合构造函数和初始化语法,这将完全覆盖 .Path
属性,而不是附加到它。
本质上...
var uriBuilder = new UriBuilder("D:\\Test");
// uriBuilder.Path is now "D:\\Test"
// ToString() will give "file:///D:/Test"
uriBuilder.Path = "locations";
// ToString() will give "file://locations", because Path is "locations"
如果您不能使用 Path.Combine,则必须编写自己的 Path.Combine。
在我非常有限的测试中,如果您假设“/”是目录分隔符,UriBuilder
似乎会做正确的事情。
var uriBuilder = new UriBuilder("D:\\Test");
uriBuilder.Path += "/locations";
// uriBuilder.ToString() == "file:///D:/Test/locations"
但是,如果 basePath
已经以“/”或“\”结尾,那么您将在 URL 中使用双斜杠。从技术上讲,这仍然是一个有效的 URL。但这很丑陋,最终可能有人会针对您提出错误。您必须处理 uriBuilder.Path
是否以“/”结尾以及 resource
是否以“/”、“\”开头的所有排列。
关于c# - UriBuilder 没有正确组合两个 URI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28776392/