Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 791
kumar Avatar asked Nov 16 '10 18:11

kumar


4 Answers

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!
}
like image 85
SLaks Avatar answered Nov 13 '22 20:11

SLaks


I had a space after "http:// " like http:// exampleServer/exampleservice.svc which had caused this error.

like image 3
Dev Avatar answered Nov 13 '22 21:11

Dev


For anyone, this could be the issue, There was Invalid URI: The hostname could not be parsed for me on some urls and one some urls it was not coming.

I looked into the urls making issue, they had '\' instead of '/' in urls,

so in URI parsing it throws error.

like image 2
Suhail Mumtaz Awan Avatar answered Nov 13 '22 22:11

Suhail Mumtaz Awan


Maybe this will help some poor soul in the future. I just spent 5 hours bashing my head against a wall trying to figure out why SpecFlow was choking on this exact error. I couldn't find the smoking gun, but I am fairly certain for me it was the path name was too long, or potentially there was something bad in the path. When I moved the solution to smaller path name it worked. Here is the SO question/answer I posted about the specifics around the error I was getting.

like image 1
DeadlyChambers Avatar answered Nov 13 '22 20:11

DeadlyChambers