Search code examples
c#error-handlinguri

Invalid URI: The hostname could not be parsed


I am trying to Construct a URI. But I am unable to handle bad URIs.

Is there any way we can handle bad URIs?

Code I am using:

if (reviews[e.Item.ItemIndex].URL.ToString().Contains("http:"))
{
      oURI = new Uri(reviews[e.Item.ItemIndex].URL.ToString());
}
else 
{
   oURI = new Uri("http://"+ reviews[e.Item.ItemIndex].URL.ToString());
}

else part gets error out for bad URIs.

Thank you!


Solution

  • Call Uri.TryCreate:

    string original = reviews[e.Item.ItemIndex].URL.ToString();
    if (!original.StartsWith("http:"))
        original = "http://" + original;
    Uri uri;
    if (!Uri.TryCreate(original, UriKind.Absolute, out uri)) {
        //Bad bad bad!
    }