none
How-To: Check if string is a valid uri

    Question

  • Hi everyone,
    I tried to check if the content of a string is a valid uri and tried two ways.

    First I use the constructor of the uri class, bit when the string is invalid, an exception is thrown.

    string myPath = "d";
    
    Uri myUri = new Uri(myPath, UriKind.Absolute); // throws an exception
    


    To prevent me from using try-catch all times I decided to use the static TryCreate-method of the uri class. But when I call this method with a invalid value, the mehtod returns true and the uri instance seems to be created. But when I acces its properties, an InvalidOperation-Exception is thrown.

    string myPath = "d";
    bool result = false;
    Uri myUri;
    
    result = Uri.TryCreate(myPath, UriKind.Absolute, out myUri);  //returns true
    
    if(result)
    {
        Console.WriteLine(myUri.Scheme);  // Throws Exception
    }
    Why does the TryCreate method returns true?

    Best Regards
    Chris


    Monday, November 23, 2009 2:07 PM

Answers

All replies