What's the difference between Uri.ToString() and Uri.AbsoluteUri?

C#.Net

C# Problem Overview


As a comment to an Azure question just now, @smarx noted

> I think it's generally better to do blob.Uri.AbsoluteUri than > blob.Uri.ToString().

Is there a reason for this? The documentation for Uri.AbsoluteUri notes that it "Gets the absolute URI", Uri.ToString() "Gets a canonical string representation for the specified instance."

C# Solutions


Solution 1 - C#

Given for example:

UriBuilder builder = new UriBuilder("http://somehost/somepath");
builder.Query = "somekey=" + HttpUtility.UrlEncode("some+value");
Uri someUri = builder.Uri;

In this case, Uri.ToString() will return a human-readable URL: http://somehost/somepath?somekey=some+value

Uri.AbsoluteUri on the other hand will return the encoded form as HttpUtility.UrlEncode returned it: http://somehost/somepath?somekey=some%2bvalue

Solution 2 - C#

Additionally: If your Uri is a relative Uri AbsoluteUri will fail, ToString() not.

Uri uri = new Uri("fuu/bar.xyz", UriKind.Relative);
string str1 = uri.ToString(); // "fuu/bar.xyz"
string str2 = uri.AbsoluteUri; // InvalidOperationException

Solution 3 - C#

Why not check and use the correct one?

string GetUrl(Uri uri) => uri?.IsAbsoluteUri == true ? uri?.AbsoluteUri : uri?.ToString();

Solution 4 - C#

Since everybody seems to think that uri.AbsoluteUri is better, but because it fails with relative paths, then probably the universal way would be:

Uri uri = new Uri("fuu/bar.xyz", UriKind.Relative);
string notCorruptUri = Uri.EscapeUriString(uri.ToString());

Solution 5 - C#

The following example writes the complete contents of the Uri instance to the console. In the example shown,

http://www.cartechnewz.com/catalog/shownew.htm?date=today

is written to the console.

Uri baseUri = new Uri("http://www.cartechnewz.com");
Uri myUri = new Uri(baseUri, "catalog/shownew.htm?date=today");
Console.WriteLine(myUri.AbsoluteUri);

The AbsoluteUri property includes the entire URI stored in the Uri instance, including all fragments and query strings.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeremy McGeeView Question on Stackoverflow
Solution 1 - C#Ofer ZeligView Answer on Stackoverflow
Solution 2 - C#ordagView Answer on Stackoverflow
Solution 3 - C#Rohit Vipin MathewsView Answer on Stackoverflow
Solution 4 - C#G. StoynevView Answer on Stackoverflow
Solution 5 - C#AKMDD KenView Answer on Stackoverflow