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

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


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

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());

Tags:

C#

.Net