How to check that a uri string is valid

C#.NetUri

C# Problem Overview


How do you check that a uri string is valid (that you can feed it to the Uri constructor)?

So far I only have the following but for obvious reasons I'd prefer a less brute way:

    Boolean IsValidUri(String uri)
    {
        try
        {
            new Uri(uri);
            return true;
        }
        catch
        {
            return false;
        }
    }

I tried Uri.IsWellFormedUriString but it doesn't seem to like everything that you can throw at the constructor. For example:

String test = @"C:\File.txt";
Console.WriteLine("Uri.IsWellFormedUriString says: {0}", Uri.IsWellFormedUriString(test, UriKind.RelativeOrAbsolute));
Console.WriteLine("IsValidUri says: {0}", IsValidUri(test));

The output will be:

Uri.IsWellFormedUriString says: False
IsValidUri says: True

Update/Answer

The Uri constructor uses kind Absolute by default. This was causing a discrepancy when I tried using Uri.TryCreate and the constructor. You do get the expected outcome if you match the UriKind for both the constructor and TryCreate.

C# Solutions


Solution 1 - C#

A well-formed URI implies conformance with certain RFCs. The local path in your example is not conformant with these. Read more in the IsWellFormedUriString documentation.

A false result from that method does not imply that the Uri class will not be able to parse the input. While the URI input might not be RFC conformant, it still can be a valid URI.

Update: And to answer your question - as the Uri documentation shows, there is a static method called TryCreate that will attempt exactly what you want and return true or false (and the actual Uri instance if true).

Solution 2 - C#

Since the accepted answer doesn't provide an explicit example, here is some code to validate URIs in C#:

Uri outUri;

if (Uri.TryCreate("ThisIsAnInvalidAbsoluteURI", UriKind.Absolute, out outUri)
   && (outUri.Scheme == Uri.UriSchemeHttp || outUri.Scheme == Uri.UriSchemeHttps))
{
    //Do something with your validated Absolute URI...
}

Solution 3 - C#

Assuming we only want to support absolute URI and HTTP requests, here is a function that does what you want:

public static bool IsValidURI(string uri)
{
    if (!Uri.IsWellFormedUriString(uri, UriKind.Absolute))
        return false;
    Uri tmp;
    if (!Uri.TryCreate(uri, UriKind.Absolute, out tmp))
        return false;
    return tmp.Scheme == Uri.UriSchemeHttp || tmp.Scheme == Uri.UriSchemeHttps;
}

Solution 4 - C#

In my case I just wanted to test the uri, I don't want to slow down the application testing the uri.

Boolean IsValidUri(String uri){
  return Uri.IsWellFormedUriString(uri, UriKind.Absolute);
}

Solution 5 - C#

Try it:

private bool IsValidUrl(string address)
    {
        return Uri.IsWellFormedUriString(address, UriKind.RelativeOrAbsolute);
    }

Solution 6 - C#

In your case the uri argument is an absolute path which refers to a file location, so as per the doc of the method it returns false. Refer to this

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionManuelView Question on Stackoverflow
Solution 1 - C#Franci PenovView Answer on Stackoverflow
Solution 2 - C#DiscDevView Answer on Stackoverflow
Solution 3 - C#cdigginsView Answer on Stackoverflow
Solution 4 - C#Glauber RodriguesView Answer on Stackoverflow
Solution 5 - C#BiBiView Answer on Stackoverflow
Solution 6 - C#Vijay SirigiriView Answer on Stackoverflow