Check if a string in C# is a URL
21,562
Solution 1
C# has Regex as well, but this seems simpler:
bool isUri = Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute);
(Answered at Regular expression for URL)
Solution 2
https://msdn.microsoft.com/en-us/library/system.web.webpages.validator.regex(v=vs.111).aspx
you use the above mentioned class or use the below regex and check Regex matches with your url string
Regex UrlMatch = new Regex(@"(?i)(http(s)?:\/\/)?(\w{2,25}\.)+\w{3}([a-z0-9\-?=$-_.+!*()]+)(?i)", RegexOptions.Singleline);
Regex UrlMatchOnlyHttps = new Regex(@"(?i)(http(s)?:\/\/)(\w{2,25}\.)+\w{3}([a-z0-9\-?=$-_.+!*()]+)(?i)", RegexOptions.Singleline);
you can also use the above regexpattern to validate the url
Solution 3
You can use this way:
bool result = Uri.TryCreate(uriName, UriKind.RelativeOrAbsolute, out uriResult)
&& uriResult.Scheme == Uri.UriSchemeHttp;
Author by
Fandango68
Updated on July 09, 2022Comments
-
Fandango68 almost 2 years
This has been asked before here, but the answers are all PHP related. Is there a similar and working solution using C#? Like a specific test class or routine? I want to parse www.google.com or google.com or mywebsite.net etc... with or without prefixes. Thanks