A better way to validate URL in C# than try-catch?

前端 未结 10 966
栀梦
栀梦 2020-12-13 12:08

I\'m building an application to retrieve an image from internet. Even though it works fine, it is slow (on wrong given URL) when using try-catch statements in the applicatio

10条回答
  •  轮回少年
    2020-12-13 12:54

    Hi you validate https http,ftp,sftp,ftps,any thing starting with www.

    string regular = @"^(ht|f|sf)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$";
    string regular123 = @"^(www.)[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$";
    
    string myString = textBox1.Text.Trim();
    if (Regex.IsMatch(myString, regular))
    {
        MessageBox.Show("It is valide url  " + myString);
    }
    else if (Regex.IsMatch(myString, regular123))
    {
        MessageBox.Show("Valide url with www. " + myString);
    }
    else 
    {
        MessageBox.Show("InValide URL  " + myString);
    }
    

提交回复
热议问题