Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine relative baseUri with relative path

Tags:

c#

asp.net

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.

like image 315
jrummell Avatar asked Feb 07 '11 19:02

jrummell


2 Answers

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

like image 195
jrummell Avatar answered Sep 18 '22 14:09

jrummell


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".

like image 29
Carlos Beppler Avatar answered Sep 18 '22 14:09

Carlos Beppler