Reputation: 1357
I'm using the following code to validate a url, but the problem that in both cases the check retruns true. How should I get false in the second option?
Here bool is true
bool isWellFormedUriString = Uri.IsWellFormedUriString("http://stackoverflow.com/", UriKind.RelativeOrAbsolute);
Here it is true as well
bool isWellFormedUriString = Uri.IsWellFormedUriString("ddddd", UriKind.RelativeOrAbsolute);
and now when I do
_uri = new Uri(_url);
I got exception ....
Upvotes: 3
Views: 8976
Reputation: 37848
Try this:
Uri result;
if (Uri.TryCreate("http://stackoverflow.com",UriKind.Absolute, out result) &&
result.Scheme == Uri.UriSchemeHttp)
{
//Use the valid Uri here
}
I restricted the valid schemes because otherwise even directories URIs would be valid (Ex: c:\\directory\\filename
)
Upvotes: 7
Reputation: 66469
The string ddddd
could be a valid "part" of a full URI, so using Relative
or RelativeOrAbsolute
returns true.
Try changing the second parameter to UriKind.Absolute
:
bool isWellFormedUriString // returns true
= Uri.IsWellFormedUriString("http://stackoverflow.com/", UriKind.Absolute);
bool isWellFormedUriString // returns false
= Uri.IsWellFormedUriString("ddddd", UriKind.Absolute);
From the docs:
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).
Upvotes: 8