Today I was working with System.Uri class a bit and I must say that it is very useful. Just imagine checking if a given URL is absolute or getting the host name from URL or even getting the query part. All of this is implemented in this one class by means of properties like IsAbsoluteUri, Host, Query etc. There is however one problem...
While playing with System.Uri I encountered a situation where while trying to create an Uri object I got the following exception:
System.UriFormatException was unhandled
Message="Invalid URI: The format of the URI could not be determined."
Source="System"
StackTrace:
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString)
Of course there is nothing wrong with it. Not every string represents an Uri. So, remembering about the pattern found in classes such as Boolean or Int32 I looked for a TryParse method. As it came out, System.Uri doesn't have a TryParse method but there is TryCreate method instead. After changing the code to use TryCreate method and running the application it came out that I still have a problem somewhere.
At first I thought that the problem was the TryCreate method! In all cases where the normal constructor failed for me, the TryCreate method not only returned true, but also constructed a System.Uri object!
The following code demonstrates the issue:
string url = "asdasda";
Uri uri;
if (!Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out uri))
{
}
else
{
uri = new Uri(url);
}
The above code should run smoothly, but it will throw the mentioned System.UriFormatException. The reason for this is that when using the constructor, we should also use the overload that allows us to pass the UriKind as an argument!