我正在寻找一种干净的方式来将相对基础Uri与另一条相对路径相结合.我试过以下,但Uri(Uri, string)并UriBuilder(Uri)要求绝对URI(抛出InvalidOperationException异常:不支持该操作相对URI).
// where Settings.Default.ImagesPath is "~/path/to/images"
// attempt 1
_imagePath = new Uri(Settings.Default.ImagesPath, image);
// attempt 2
UriBuilder uriBuilder = new UriBuilder(Settings.Default.ImagesPath);
uriBuilder.Path += image;
_imagePath = uriBuilder.Uri;
Run Code Online (Sandbox Code Playgroud)
我不想做任何丑陋的字符串操作,以确保基本路径以尾部斜杠结束等.
jru*_*ell 18
这仍然比我想要的有点麻烦,但它确实有效.
public static class UriExtensions
{
public static Uri Combine(this Uri relativeBaseUri, Uri relativeUri)
{
if (relativeBaseUri == null)
{
throw new ArgumentNullException("relativeBaseUri");
}
if (relativeUri == null)
{
throw new ArgumentNullException("relativeUri");
}
string baseUrl = VirtualPathUtility.AppendTrailingSlash(relativeBaseUri.ToString());
string combinedUrl = VirtualPathUtility.Combine(baseUrl, relativeUri.ToString());
return new Uri(combinedUrl, UriKind.Relative);
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个示例用法:
Uri imageUrl = new Uri("profile.jpg", UriKind.Relative);
Uri baseImageUrl = new Uri("~/path/to/images", UriKind.Relative);
Uri combinedImageUrl = baseImageUrl.Combine(image);
Run Code Online (Sandbox Code Playgroud)
combinedImageUrl是〜/ path/to/images/profile.jpg
尝试:
UriBuilder builder = new UriBuilder();
Uri baseUri = builder.Uri;
builder.Path = Settings.Default.ImagesRealtivePath;
if (!builder.Path.EndsWith("/"))
builder.Path += "/";
_imagePath = baseUri.MakeRelativeUri(new Uri(builder.Uri, image));
Run Code Online (Sandbox Code Playgroud)
这将返回字符串“~/path/to/images/image.jpg”。
| 归档时间: |
|
| 查看次数: |
17877 次 |
| 最近记录: |