Search code examples
c#httpwebrequestwebproxy

C# check if a string is a valid WebProxy format


so after searching both on here and Google I have been unable to find a solution. Basically I want to allow the user to add a list of proxies from a text file, but I want to check that what gets passed in is a valid Proxy format before I make the WebProxy. I know using try catch like try {var proxy = new WebProxy(host + ":" + port;} catch{} will work, but as you may already know using try catch is slow, even more so when doing it in bulk.

So what would be a good and fast way to test a string to see if it's in a valid WebProxy format?

Thanks


Solution

  • This is how I do it:

    var ValidIpAddressPortRegex = @"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]):[\d]+$";
    if (System.Text.RegularExpressions.Regex.IsMatch(proxy_string_to_validate, ValidIpAddressPortRegex ))
    {
        do_stuff_with_proxy();
    }
    else
    {
        //MessageBox.Show("IP:PORT url not valid!","Information");
    }