How to check if a given url is http or https in c#?

Member

by kadin , in category: Third Party Scripts , 3 months ago

How to check if a given url is http or https in c#?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 3 months ago

@kadin 

You can check if a given URL is using the HTTP or HTTPS protocol in C# by first parsing the URL and then checking the scheme property of the parsed URL. Here is an example code snippet to demonstrate this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;

class Program
{
    static void Main()
    {
        string url = "https://www.example.com";
        
        // Parse the URL
        Uri uri = new Uri(url);
        
        // Check if the scheme is HTTP or HTTPS
        if (uri.Scheme == Uri.UriSchemeHttp)
        {
            Console.WriteLine("The URL is using HTTP protocol");
        }
        else if (uri.Scheme == Uri.UriSchemeHttps)
        {
            Console.WriteLine("The URL is using HTTPS protocol");
        }
        else
        {
            Console.WriteLine("The URL is using a different protocol");
        }
    }
}


In this code snippet, the given URL "https://www.example.com" is parsed using the Uri class and then the Scheme property of the parsed URL is checked to determine if it is using HTTP or HTTPS protocol.