I'm looking for a clean way to combine a relative base Uri with another relative path. I've tried the following, but Uri(Uri, string)
and UriBuilder(Uri)
require absolute Uris (throwing InvalidOperationException: This operation is not supported for a relative 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;
I don't want to do any ugly string manipulation to make sure the base path ends with a trailing slash, etc.
This is still a bit messier than I'd like, but it works.
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);
}
}
Here's an example usage:
Uri imageUrl = new Uri("profile.jpg", UriKind.Relative);
Uri baseImageUrl = new Uri("~/path/to/images", UriKind.Relative);
Uri combinedImageUrl = baseImageUrl.Combine(image);
The combinedImageUrl is ~/path/to/images/profile.jpg
Try:
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));
This will return the string "~/path/to/images/image.jpg".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With