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

As a comment on the Azure question just now, @smarx noted

I think it's 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 the canonical string representation for the specified instance."

+62
c #
Oct 02 '11 at 6:41
source share
4 answers

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 since HttpUtility.UrlEncode returned it: http://somehost/somepath?somekey=some%2bvalue

+72
Oct 02 '11 at 6:44
source share

Optional: If your Uri is a relative Uri AbsoluteUri , it will not execute, ToString() not.

 Uri uri = new Uri("fuu/bar.xyz", UriKind.Relative); string str1 = uri.ToString(); // "fuu/bar.xyz" string str2 = uri.AbsoluteUri; // InvalidOperationException 
+22
Oct 02 '11 at 15:59
source share

Since everyone seems to think uri.AbsoluteUri better, but since it fails with relative paths, then there is probably a universal way:

 Uri uri = new Uri("fuu/bar.xyz", UriKind.Relative); string notCorruptUri = Uri.EscapeUriString(uri.ToString()); 
+2
Mar 14 '13 at 19:01
source share

Why not check and use the right one?

 string GetUrl(Uri uri) => uri?.IsAbsoluteUri == true ? uri?.AbsoluteUri : uri?.ToString(); 
+1
Feb 17 '17 at 20:30
source share



All Articles