9

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

Community
  • 1
  • 1
Fandango68
  • 3,956
  • 3
  • 35
  • 60

3 Answers3

21

C# has Regex as well, but this seems simpler:

bool isUri = Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute);

(Answered at Regular expression for URL)

Community
  • 1
  • 1
user2357661
  • 234
  • 2
  • 2
  • 1
    This worked for me. The Uri.TryCreate() methods mentioned always returned NULL because the url I am pasrsing is simply something like "www.google.com". It may or may not contain HTTP or HTTPS or FTP, etc – Fandango68 Mar 19 '15 at 05:25
  • For me does not work. I've tested "www.google.com" and will pass, next I've tested "w" and pass the same. It will does not check correctly. – Marco Concas May 14 '19 at 10:08
3

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

1

You can use this way:

bool result = Uri.TryCreate(uriName, UriKind.RelativeOrAbsolute, out uriResult) 
              && uriResult.Scheme == Uri.UriSchemeHttp;
Santosh Panda
  • 7,089
  • 8
  • 41
  • 54
  • What about HTTPS and what if I don't have those prefixes? I want to check www.google.com for example or even google.com – Fandango68 Mar 19 '15 at 05:26