Search code examples
c#webview2

How to differentiate between a string and a url easier in c# WinForms WebView2


So I have this giant monstrosity of code, which works as expected, goes to the respective URL and if it's not a URL it goes to search for the string(s). The problem is

  1. the websites that are down but exist or don't give a response are deemed as not a URL and therefore are being searched for instead
  2. pinging the same site too many times leads to being blocked, eg google.
  3. The ping method takes too long to respond.
[...]
            try
            {
                timer1.Start();
                if (SearchBox.Text.Contains(SearchBox.Text.ToString()))
                {
                    if (webView21 != null && webView21.CoreWebView2 != null)
                    {
                        Ping pingSender = new Ping();
                        PingOptions options = new PingOptions();

                        // Use the default Ttl value which is 128,
                        // but change the fragmentation behavior.
                        options.DontFragment = true;

                        // Create a buffer of 32 bytes of data to be transmitted.
                        string data = "aaa";
                        byte[] buffer = Encoding.ASCII.GetBytes(data);
                        int timeout = 0;
                        PingReply reply = pingSender.Send(SearchBox.Text.ToString(), timeout, buffer, options);
                        if (reply.Status == IPStatus.Success)
                        {
                            if (SearchBox.Text.StartsWith("https://"))
                            {
                                webView21.CoreWebView2.Navigate(SearchBox.Text);
                            }
                            else if (SearchBox.Text.StartsWith("http://"))
                            {
                                webView21.CoreWebView2.Navigate(SearchBox.Text);
                            }
                            else
                            {
                                webView21.CoreWebView2.Navigate("https://" + SearchBox.Text);
                            }


                        }
                        else
                        {
                            webView21.CoreWebView2.Navigate("https://duckduckgo.com/?q=" + SearchBox.Text + "&t=h_&ia=web");
                        }


                    }
                }
                else if (SearchBox.Text.StartsWith("https://"))
                {
                    if (webView21 != null && webView21.CoreWebView2 != null)
                    {
                        webView21.CoreWebView2.Navigate(SearchBox.Text);

                    }
                }
                else if (SearchBox.Text.StartsWith("http://"))
                {
                    if (webView21 != null && webView21.CoreWebView2 != null)
                    {
                        webView21.CoreWebView2.Navigate(SearchBox.Text);

                    }
                }
                else
                {
                    if (webView21 != null && webView21.CoreWebView2 != null)
                    {
                        webView21.CoreWebView2.Navigate(SearchBox.Text);

                    }
                }
                
                
            }
            catch
            {
                timer1.Start();
                webView21.CoreWebView2.Navigate("https://duckduckgo.com/?q=" + SearchBox.Text + "&t=h_&ia=web");

            }
        }

Does anybody know how I could improve on this? How can I make my web browser more efficient at this. Regex maybe?


Solution

  • TBH i think you can replace your whole code with something like this:

            string userInputtedString = SearchBox.Text;
    
            // CHeck for a valid URI.
            Uri uriResult;
            bool validUrlResult = Uri.TryCreate(userInputtedString, UriKind.Absolute, out uriResult)
                          && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
    
            if (validUrlResult)
            {
                webView21.CoreWebView2.Navigate(userInputtedString);
            }
            else
            {
                // We haven't gotten a valid url, so we're gonna search instead.
                webView21.CoreWebView2.Navigate("https://duckduckgo.com/?q=" + userInputtedString + "&t=h_&ia=web");
            }
    

    EDIT:

    Apparently Uri requires a scheme (http:// or https:// or file:// etc) for the Uri class to be constructed. Hence why google.com fails - the browser automatically adds the http(s):// scheme which is why it works if you type it in the browser.

    I think for your case you can try the other answers:

    bool IsValidURL(string URL)
    {
        string Pattern = @"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$";
        Regex Rgx = new Regex(Pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
        return Rgx.IsMatch(URL);
    }
    

    So that would become something like:

            string userInputtedString = SearchBox.Text;
    
            // CHeck for a valid URI.
            Uri uriResult;
            bool validUrlResult = IsValidURL(userInputtedString);
    
            if (validUrlResult)
            {
                webView21.CoreWebView2.Navigate(userInputtedString);
            }
            else
            {
                // We haven't gotten a valid url, so we're gonna search instead.
                webView21.CoreWebView2.Navigate("https://duckduckgo.com/?q=" + userInputtedString + "&t=h_&ia=web");
            }
    

    Check if that improves your use-case.