How to check if uri string is correct

How do you check if the uri string is correct (which you can pass it to the Uri constructor)?

So far I have only had the following, but for obvious reasons, I would prefer a less crude way:

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

I tried Uri.IsWellFormedUriString, but it doesn't seem to me that everything you can throw in 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 / Reply

The default Uri constructor uses the good Absolute. This caused a mismatch when I tried to use Uri.TryCreate and the constructor. You will get the expected result if you agree with UriKind for both the constructor and TryCreate.

Thank,

+45
c # uri
Jan 29 2018-11-11T00:
source share
4 answers

A well-formed URI implies compliance with specific RFCs. The local path in your example does not match these. Read more in the IsWellFormedUriString documentation.

The false result of this method does not mean that the Uri class will not be able to parse the input. Although the input URI may not be RFC compliant, it may still be a valid URI.

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

+50
Jan 29 '11 at 5:19
source share

Since the accepted answer does not contain an explicit example, here is some code to check the URI 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... } 
+21
Sep 03 '14 at 21:51
source share

Assuming we want to support only 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; } 
+3
Nov 06 '15 at 18:29
source share

In your case, the uri argument is an absolute path that refers to the location of the file, since in the method doc it returns false. See this

0
Jan 29 '11 at 5:15
source share



All Articles