Tri Nguyen Dung
Tri Nguyen Dung

Reputation: 959

How to check if youtube url in C#

I want to check if an given URL a is link to http://youtube.com.

I know there are lots of various shortened version's of the links (e.g. http://youtu.be), so what I am after is a way to resolve the URL and see if it ends up as http://youtube.com.

A couple of example inputs are:

http://www.youtube.com/v/[videoid]
http://www.youtu.be/watch?v=[videoid]

Does anyone know of a way to do this?

Upvotes: 0

Views: 3948

Answers (4)

smedasn
smedasn

Reputation: 1409

                    bool isYoutube = false;

                    string host = new Uri(url).Host;
                    if (host == "youtube.com" || host == "youtu.be")
                    {
                        isYoutube = true;
                    }

Upvotes: 2

wRAR
wRAR

Reputation: 25693

If you want to know whether a given URL redirects (using status codes 301/302) to an YouTube URL, you may either use WebClient/HttWebRequest/whatever directly and check the response, or disable HttpWebRequest.AllowAutoRedirect and traverse all redirects manually (checking the status code and then the Location HTTP header).

Upvotes: 0

Simon Whitehead
Simon Whitehead

Reputation: 65077

You could perform a HEAD request:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.youtu.be/Ddn4MGaS3N4");
request.Method = "HEAD";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
    Console.WriteLine("Does this resolve to youtube?: {0}", response.ResponseUri.ToString().Contains("youtube.com") ? "Yes" : "No");
}

Appears to work fine. Unsure of edge cases but seems to do the job.

(Note: No error checking here such as 404 errors, etc).

Upvotes: 3

evanmcdonnal
evanmcdonnal

Reputation: 48096

First you may have to check what the hostname is for youtube (I'm just assuming it is http://youtube.com) but after you have that the following code will do what you want;

 using System.Net;

 IPHostEntry host = Dns.Resolve(theInputHostName);
 if (host.HostName == "http://youtube.com")
      // it resolves to youtube, do something.

Upvotes: 1

Related Questions