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.
Uri(String, UriKind) Initializes a new instance of the Uri class with the specified URI. This constructor allows you to specify if the URI string is a relative URI, absolute URI, or is indeterminate. Uri(Uri, String) Initializes a new instance of the Uri class based on the specified base URI and relative URI string.
For a URI to be valid, you only have to verify it against this syntax. Connecting to it verifies that a server is registered for and listening to that URI which 1. is an entirely separate condition from the validity of the URI itself, 2.
A URL is a valid URL if at least one of the following conditions holds: The URL is a valid URI reference [RFC3986]. The URL is a valid IRI reference and it has no query component. [RFC3987] The URL is a valid IRI reference and its query component contains no unescaped non-ASCII characters.
Remarks. Absolute URIs are characterized by a complete reference to the resource (example: http://www.contoso.com/index.html ), while a relative URI depends on a previously defined base URI (example: /index. html ). The following list shows some APIs that use the UriKind enum: Uri.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With