Making urls absolute

Have you even been in a situation where you have written code like this in C#?

Example 1:



Example 2:

url = "" + url;

Or something similar?


If that is the case you need to reconsider you practice. Doing the above will probably work in 95 % of the test cases that you can think of, but what happens in the rest of the cases.


Let’s try some samples.

In example 1, would you code work properly in the following scenarios?

- if your url starts with https:// og ftp:// og some other scheme

- if your url looks like this


So instead of doing some kind of text verification of the Url, you should use the built-in function in C#. In example 1 you probably wanted to test if the url that you had was a full Uri. This can be tested by doing this

Uri.IsWellFormedUriString(url1, UriKind.Absolute)



For the second example would your code work properly in the following scenario?

- if your url was “samplepage.html” or other urls missing the /


Instead you should use this code, which ensures that the url is handled properly and as expected

new Uri(new Uri(""), "somepage.html").ToString()