Click here to Skip to main content
Click here to Skip to main content

YouTube Downloader Using C# .NET

By , 18 Feb 2013
 

Thanks again to CircleDock the Downloader works better.

Introduction 

This article shows how to download YouTube videos using C# code only. The code is very simple to understand and anyone can easily integrate it to in their solution or project.

I didn't use any third party library to do this task. All you need is to take two .cs files and integrate them to your project.

Using the code

There are two main classes in this project:

YouTubeVideoQuality Class

This is the entity that describes the video.

public class YouTubeVideoQuality 
{
    /// <summary>
    /// Gets or Sets the file name
    /// </summary>
    public string VideoTitle { get; set; }
    /// <summary>
    /// Gets or Sets the file extention
    /// </summary>
    public string Extention { get; set; }
    /// <summary>
    /// Gets or Sets the file url
    /// </summary>
    public string DownloadUrl { get; set; }
    /// <summary>
    /// Gets or Sets the youtube video url
    /// </summary>
    public string VideoUrl { get; set; }
    /// <summary>
    /// Gets or Sets the file size
    /// </summary>
    public Size Dimension { get; set; }

    public override string ToString()
    {
        return Extention + " File " + Dimension.Width + 
                           "x" + Dimension.Height;
    }

    public void SetQuality(string Extention, Size Dimension)
    {
        this.Extention = Extention;
        this.Dimension = Dimension;
    }
}

YouTubeDownloader Class

This class downloads YouTube videos:

public class YouTubeDownloader
{
    public static List<YouTubeVideoQuality> GetYouTubeVideoUrls(params string[] VideoUrls)
    {
        List<YouTubeVideoQuality> urls = new List<YouTubeVideoQuality>();
        foreach (var VideoUrl in VideoUrls)
        {
            string html = Helper.DownloadWebPage(VideoUrl);
            string title = GetTitle(html);
            foreach (var videoLink in ExtractUrls(html))
            {
                YouTubeVideoQuality q = new YouTubeVideoQuality();
                q.VideoUrl = VideoUrl;
                q.VideoTitle = title;
                q.DownloadUrl = videoLink + "&title=" + title;
                if (getQuality(q))
                    urls.Add(q);
            }
        }
        return urls;
    }

    private static string GetTitle(string RssDoc)
    {
        string str14 = Helper.GetTxtBtwn(RssDoc, "'VIDEO_TITLE': '", "'", 0);
        if (str14 == "") str14 = Helper.GetTxtBtwn(RssDoc, "\"title\" content=\"", "\"", 0);
        if (str14 == "") str14 = Helper.GetTxtBtwn(RssDoc, "&title=", "&", 0);
        str14 = str14.Replace(@"\", "").Replace("'", "&#39;").Replace(
                "\"", "&quot;").Replace("<", "&lt;").Replace(
                ">", "&gt;").Replace("+", " ");
        return str14;
    }


    private static List<string> ExtractUrls(string html)
    {
        html = Uri.UnescapeDataString(Regex.Match(html, "url_encoded_fmt_stream_map=(.+?)&", 
                                      RegexOptions.Singleline).Groups[1].ToString());
        MatchCollection matchs = Regex.Matches(html, 
          "url=(.+?)&quality=(.+?)&fallback_host=(.+?)&type=(.+?)&itag=(.+?),", 
          RegexOptions.Singleline);
        bool firstTry = matchs.Count > 0;
        if (!firstTry)
            matchs = Regex.Matches(html, 
                     "itag=(.+?)&url=(.+?)&type=(.+?)&fallback_host=(.+?)&sig=(.+?)&quality=(.+?),{0,1}", 
                     RegexOptions.Singleline);
        List<string> urls = new List<string>();
        foreach (Match match in matchs)
        {
            if (firstTry)
                urls.Add(Uri.UnescapeDataString(match.Groups[1] + ""));
            else urls.Add(Uri.UnescapeDataString(match.Groups[2] + "") + "&signature=" + match.Groups[5]);
        }
        return urls;
    }

    private static bool getQuality(YouTubeVideoQuality q)
    {
        if (q.DownloadUrl.Contains("itag=5"))
            q.SetQuality("flv", new Size(320, 240));
        else if (q.DownloadUrl.Contains("itag=34"))
            q.SetQuality("flv", new Size(400, 226));
        else if (q.DownloadUrl.Contains("itag=6"))
            q.SetQuality("flv", new Size(480, 360));
        else if (q.DownloadUrl.Contains("itag=35"))
            q.SetQuality("flv", new Size(640, 380));
        else if (q.DownloadUrl.Contains("itag=18"))
            q.SetQuality("mp4", new Size(480, 360));
        else if (q.DownloadUrl.Contains("itag=22"))
            q.SetQuality("mp4", new Size(1280, 720));
        else if (q.DownloadUrl.Contains("itag=37"))
            q.SetQuality("mp4", new Size(1920, 1280));
        else if (q.DownloadUrl.Contains("itag=38"))
            q.SetQuality("mp4", new Size(4096, 72304));
        else return false;
        return true;
    }
}

Points of Interest

Using this code you can select the video quality depending in your internet connection speed to start download.

Many people have slow internet connections and they can not watch videos from YouTube, so I made this code to help those people to download YouTube videos to their PC's so they can watch the videos offline.

Updates

Thanks to Motaz Alnuweiri, the Downloader works again. Added self download videos.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

akramKamal
Software Developer Desktop Team
Palestinian Territory (Occupied) Palestinian Territory (Occupied)
Member
I have advanced skills in desktop apps development, i have built many apps for many corporations.
 
i'm using the follow languages in my work:
1- C# Language.
2- VB6 Language.
3- Asp.net using C#.
4- Crystal Reports.
 
i have more than 7 experience years in coding and programming.
 
Systems and apps Developed by Us:
1-E-Archive System (VB6,Supports multi DataBase Engins).
2-SMS System (Multi languages such VB6,C#,Asp.Net and Gizmox).
3-Multi Camera Monitor System-Motion Detection and record(C#).
4-Administrative Evaluation System (Asp.net).
5-E-Clinic System (C#-using my business layer generator,Supports multi DataBase Engines).
6-Data Access Layer Generator Framework(C#).
7-Sip Provider -VOIP- Softphone (C#- for Italian company).
8-Training course Manager System(C#-for UCAS).
9-Computer Exam System (VB6,Oracle DataBase).
10-Dialer System (VB6).
11-Implement Google API using C# (Translation and web Search).
12-Print Management Enterprise(C#)
13-Elections System (C#- using my business layer generator).
14-Advanced English competition (VB6).
15-Remote USB Sharing (C/C++,VB6).
16-Watch Attendance (C/C++,VB6).
17-Tube Spy (C#).
18-AdminYourTube (C#)
19- Transport Reservation System (C#,Asp.net,Ajax,Jquery)
 
Please visit my elance URL http://ashrafnet.elance.com

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 4memberJai Mallesh1 Jan '13 - 0:45 
I wanted to give 5 starts. But I am giving 4 as there are some fixes required. The application cannot catch the URLs. I have to try 3 times to get the download started.
GeneralRe: My vote of 4memberakramKamal1 Jan '13 - 3:32 
That's because youtube changes the syntax of the html source code for each request.
QuestionRe: My vote of 4memberEmpire44310 Feb '13 - 9:36 
is there any way to fix that ?
QuestionNew Version PostedmemberakramKamal28 Dec '12 - 10:49 
Hi everyone
I am sorry for being late, i was very busy, i have a big project in my hand.
 
I posted a new working version taking in my account all the useful comments from you people; waiting for the code project team to approve it.
 
I really thankful for all users who take care of my software and i hope always i have this concern.
 
Thanks,
Akram
AnswerRe: New Version Posted [modified]memberDiabloPB29 Dec '12 - 0:00 
Hi Akram
first of all, nice work! its help me to build my own youtube downloader Wink | ;)
but also in the new version is the download-url in some videos not correct. after the signature is coming an decimal point sometimes. As a result I can't download the video.
 
sorry for my english Smile | :)
 
EDIT: please try this video: http://www.youtube.com/watch?v=c0wI7dfVSoI sometimes it works fine, sometimes it don't work.
http://www.pb-software.de.vu


modified 29 Dec '12 - 6:13.

NewsRe: New Version PostedmemberMotaz Alnuweiri29 Dec '12 - 3:51 
Hi, try my program.
 
Download:
http://www.mediafire.com/?3sn85qi6d75aeta[^]
GeneralRe: New Version PostedmemberDiabloPB29 Dec '12 - 5:06 
Motaz Alnuweiri wrote:
Hi, try my program.

 

Download:

http://www.mediafire.com/?3sn85qi6d75aeta[^]

 
Thank you! Exactly the same with the decimal point I have now also implemented.
 
e.g.:
if (url.EndsWith(","))
                    {
                        url = url.Remove(url.Length - 1, 1);
                    }
http://www.pb-software.de.vu

GeneralRe: New Version PostedmemberakramKamal29 Dec '12 - 3:57 
Hi
the url worked fine, please try the last version
 
Thanks,
Akram
QuestionNot workingmemberkabila28 Dec '12 - 4:42 
Hi
 
This application throws error "The remote server error:403 Forbidden" when i download youtube URL.
 
Can u plz help me...
 
Regards
 
Kabi
BugDEC 25 version not working for mememberTheFigmo27 Dec '12 - 10:01 
When I "Get Video" it displays the thumb OK - and gives me a list of quality choices - but all of them say "0 Bytes" next to them. If I try to download any of the choices anyway - I see the "File Downloader" form - but it just stays at 0% forever - no downloading.
 
Wow - I must say - when I first started looking for some c# code to DL youtube vids this morning I budgeted about half an hour for the task. HA HA HA Obviously - this is a MUCH bigger problem than I thought. Seems youtube is constantly changing their interface to discourage downloads. Maybe we could store a regex expression or something in a registry entry to make it easy to keep up with the constant page changes?
 
I dunno. I'd like get some code working first and then look at making it more "future friendly". Yours is like the 5th code sample I've tried and I have yet to download a single vid. Frustrating. Hope you can get it working again.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 18 Feb 2013
Article Copyright 2012 by akramKamal
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid