des
des

Reputation: 67

Determining path of a relative URL without filename

I use this simple code to retrieve the absolute path from the links I parse from a web page. CurrentAddress is the webpage address, testingAddress is the link I found

String uri = new Uri(new Uri(currentAddress), new Uri(testingAddress)).AbsoluteUri;

This works pretty much always and it can discern whether or not the testingAddress is relative to the page or not.

I'm getting a problem with relative links that do not specify a filename, for example "/portal/combo/?v=1"

In that case the exception

"the format of the URI could not be determined"

gets raised.

If I specify the testingAddress is relative it works, but at that point I lose the functionality of the code that was meant to be able to understand how to combine paths on its own and I have to check the paths manually before joining them.

Is there a way to make this work or I have to suck it up and add controls to preparse the testingAddress string?

Upvotes: 0

Views: 688

Answers (1)

tmaj
tmaj

Reputation: 34957

Use the overload that takes in string? as the second parameter (from documentation):

Uri(Uri, String)

Initializes a new instance of the Uri class based on the specified base URI and relative URI string.

public Uri (Uri baseUri, string? relativeUri);

Example

var currentAddress = "https://stackoverflow.com";
var testingAddress = "/questions/67382787/determining-path-of-a-relative-url-without-filename";
String uri = new Uri(
    baseUri: new Uri(currentAddress), 
    relativeUri: testingAddress).AbsoluteUri;

// uri is "https://stackoverflow.com/questions/67382787/determining-path-of-a-relative-url-without-filename"

Upvotes: 2

Related Questions