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

YouTube Downloader Using C# .NET

, 24 Nov 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Full C# code to download videos from YouTube in any quality.

Attached new version Smile | :) .

Introduction

This tip 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 on your internet connection speed to start download.

Many people have slow internet connections and they cannot watch videos from YouTube, so I made this code to help those people to download YouTube videos to their PCs 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)

Share

About the Author

akramKamal
Software Developer Desktop Team
Palestinian Territory (Occupied) Palestinian Territory (Occupied)
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

Comments and Discussions

 
GeneralRe: Improved version PinmemberCeyhun Emre Bozkurt1-Aug-13 23:42 
GeneralRe: Improved version PinmemberMotaz Alnuweiri2-Aug-13 4:52 
GeneralRe: Improved version PinmemberCeyhun Emre Bozkurt3-Aug-13 3:42 
GeneralMy vote of 5 [modified] Pinmembernabilchaoui13-Nov-12 10:31 
GeneralRe: My vote of 5 PinmemberakramKamal14-Nov-12 0:44 
QuestionNot working PinmemberF. ARO3-Nov-12 5:50 
AnswerRe: Not working PinmemberakramKamal3-Nov-12 7:02 
GeneralRe: Not working PinmemberF. ARO4-Nov-12 4:17 
GeneralRe: Not working PinmemberakramKamal4-Nov-12 5:50 
GeneralRe: Not working PinmemberF. ARO4-Nov-12 8:57 
GeneralRe: Not working PinmemberakramKamal4-Nov-12 10:56 
GeneralMy vote of 5 PinmemberJustinoScalabitano30-Oct-12 0:48 
Questionits really great Pinmembersmaker21-Oct-12 9:54 
AnswerRe: its really great PinmemberakramKamal21-Oct-12 10:47 
Thanks for your interesting,
to download as mp3 we need to add a converter option, i will add this option later because i am too busy these days
BUT, its up to you to search for a c# converter and then combine it with the downloader code
 
Thanks,
Akram
GeneralMy vote of 5 Pinmembergeekbond17-Oct-12 5:44 
QuestionBookmarked ! PinmemberGun Gun Febrianza16-Oct-12 17:43 
AnswerRe: Bookmarked ! PinmemberakramKamal17-Oct-12 3:09 
GeneralRe: Bookmarked ! PinmemberGun Gun Febrianza17-Oct-12 22:33 
GeneralRe: Bookmarked ! PinmemberakramKamal18-Oct-12 6:10 
GeneralRe: Bookmarked ! PinmemberGun Gun Febrianza19-Oct-12 2:17 
GeneralRe: Bookmarked ! PinmemberakramKamal19-Oct-12 3:03 
GeneralRe: Bookmarked ! PinmemberGun Gun Febrianza19-Oct-12 16:21 
GeneralRe: Bookmarked ! PinmemberakramKamal20-Oct-12 3:51 
GeneralMy vote of 5 PinmemberGun Gun Febrianza16-Oct-12 17:42 
GeneralMy vote of 5 Pinmemberjjlangatjose16-Oct-12 8:07 
QuestionThanks PinmemberShabanaParveen15-Oct-12 19:43 
Questionimplementing downloader PinmemberFatih Akgun12-Oct-12 20:25 
AnswerRe: implementing downloader PinmemberakramKamal14-Oct-12 7:06 
GeneralRe: implementing downloader PinmemberFatih Akgun15-Oct-12 2:17 
GeneralMy vote of 5 PinmemberYaroslav Tatarenko26-Sep-12 21:07 
GeneralMy vote of 5 PinmemberVinicius G. A. de Oliveira24-Sep-12 9:11 
GeneralRe: My vote of 5 PinmemberakramKamal24-Sep-12 9:25 
GeneralRe: My vote of 5 PinmemberVinicius G. A. de Oliveira24-Sep-12 9:43 
GeneralRe: My vote of 5 PinmemberakramKamal14-Oct-12 7:10 
Question5 out of 5 [modified] PinmemberMember 826886824-Sep-12 8:42 
AnswerRe: Broken download link PinmemberakramKamal27-Sep-12 0:09 
QuestionIt's working now! PinmvpOriginalGriff24-Sep-12 5:25 
AnswerRe: It's working now! PinmemberakramKamal24-Sep-12 5:28 
GeneralMy vote of 5 PinmemberHoussem Dellai23-Sep-12 8:45 
QuestionNot working Pinmemberporcelli16-Sep-12 20:09 
AnswerRe: Not working PinmemberakramKamal17-Sep-12 10:50 
AnswerRe: Not working PinmemberakramKamal24-Sep-12 5:39 
QuestionHow you decode the Video Info. PinmemberHenry Rosales Parra10-Sep-12 11:18 
AnswerRe: How you decode the Video Info. PinmemberakramKamal10-Sep-12 12:06 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.1411023.1 | Last Updated 24 Nov 2014
Article Copyright 2014 by akramKamal
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid