Click here to Skip to main content
11,430,829 members (77,119 online)
Click here to Skip to main content

YouTube Downloader Using C# .NET

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

Thanks everyone for your help in this project, your comments and suggests were very helpful for the project.

A new version of YouTube Downloader is released on 08 Feb 2015

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 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 youtube video size
        /// </summary>
        public long VideoSize { get; set; }
        /// <summary>
        /// Gets or Sets the youtube video dimension
        /// </summary>
        public Size Dimension { get; set; }
        /// <summary>
        /// Gets the youtube video length
        /// </summary>
        public long Length { get; set; }
        public override string ToString()
        {
            string videoExtention = this.Extention;
            string videoDimension = formatSize(this.Dimension);
            string videoSize = String.Format
            (new FileSizeFormatProvider(), "{0:fs}", this.VideoSize);

            return String.Format
            ("{0} ({1}) - {2}", videoExtention.ToUpper(), videoDimension, videoSize);
        }

        private string formatSize(Size value)
        {
            string s = value.Height >= 720 ? " HD" : "";
            return ((Size)value).Width + " x " + value.Height + s;
        }
    }

YouTubeDownloader Class

This class downloads YouTube videos:

  public static class YouTubeDownloader
    {
        public static List<YouTubeVideoQuality> GetYouTubeVideoUrls(string VideoUrl)
        {
            var list = new List<YouTubeVideoQuality>();

            var id = YouTubeDownloader.GetVideoIDFromUrl(VideoUrl);
            var infoUrl = string.Format
            ("http://www.youtube.com/get_video_info?&video_id=
            {0}&el=detailpage&ps=default&eurl=&gl=US&hl=en", id);
            var infoText = new WebClient().DownloadString(infoUrl);
            var infoValues = HttpUtility.ParseQueryString(infoText);
            var title = infoValues["title"];
            var videoDuration = infoValues["length_seconds"];
            var videos = infoValues["url_encoded_fmt_stream_map"].Split(',');
            foreach (var item in videos)
            {
                try
                {
                    var data = HttpUtility.ParseQueryString(item);
                    var server = Uri.UnescapeDataString(data["fallback_host"]);
                    var url = Uri.UnescapeDataString(data["url"]) + 
                    "&fallback_host=" + server;
                    var size = getSize(url);
                    var videoItem = new YouTubeVideoQuality();
                    videoItem.DownloadUrl = url;
                    videoItem.VideoSize = size;
                    videoItem.VideoTitle = title;
                    var tagInfo = new ITagInfo(Uri.UnescapeDataString(data["itag"]));
                    videoItem.Dimension = tagInfo.VideoDimensions;
                    videoItem.Extention = tagInfo.VideoExtentions;
                    videoItem.Length = long.Parse(videoDuration);
                    list.Add(videoItem);
                }
                catch { }
            }

            return list;
        }

        private static long getSize(string videoUrl)
        {
            HttpWebRequest fileInfoRequest = (HttpWebRequest)HttpWebRequest.Create(videoUrl);
            fileInfoRequest.Proxy = Helper.InitialProxy();
            HttpWebResponse fileInfoResponse = (HttpWebResponse)fileInfoRequest.GetResponse();
            long bytesLength = fileInfoResponse.ContentLength;
            fileInfoRequest.Abort();
            return bytesLength;
        }

        /// <summary>
        /// Get the ID of a youtube video from its URL
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetVideoIDFromUrl(string url)
        {
            url = url.Substring(url.IndexOf("?") + 1);
            char[] delimiters = { '&', '#' };
            string[] props = url.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

            string videoid = "";
            foreach (string prop in props)
            {
                if (prop.StartsWith("v="))
                {
                    videoid = prop.Substring(prop.IndexOf("v=") + 2);
                }
            }

            return videoid;
        }
    }

ITagInfo struct

This struct defines the itag information for videos:

 public struct ITagInfo
    {
        const string itagExtentions = "5=flv,6=flv,17=3gp,18=mp4,22=mp4,34=flv,
        35=flv,36=3gp,37=mp4,38=mp4,43=webm,44=webm,45=webm,46=webm,82=3D.mp4,83=3D.mp4,
        84=3D.mp4,85=3D.mp4,100=3D.webm,101=3D.webm,102=3D.webm,120=live.flv";
        const string itagWideDimensions = "5=320x180,6=480x270,17=176x99,18=640x360,
        22=1280x720,34=640x360,35=854x480,36=320x180,37=1920x1080,38=2048x1152,43=640x360,
        44=854x480,45=1280x720,46=1920x1080,82=480x270,83=640x360,84=1280x720,85=1920x1080,
        100=640x360,101=640x360,102=1280x720,120=1280x720";
        const string itagDimensions = "5=320x240,6=480x360,17=176x144,18=640x480,
        22=1280x960,34=640x480,35=854x640,36=320x240,37=1920x1440,38=2048x1536,43=640x480,
        44=854x640,45=1280x960,46=1920x1440,82=480x360,83=640x480,84=1280x960,85=1920x1440,
        100=640x480,101=640x480,102=1280x960,120=1280x960";

        public ITagInfo(string iTag)
            : this()
        {
            iTag = (iTag + "").Trim();
            foreach (var item in itagExtentions.Split(','))
            {
                var nameValue = item.Split('=');
                if (nameValue[0] != iTag) continue;
                VideoExtentions = nameValue[1];
            }
            foreach (var item in itagWideDimensions.Split(','))
            {
                var nameValue = item.Split('=');
                if (nameValue[0] != iTag) continue;
                var widthAndHeight = nameValue[1].Split('x');
                VideoDimensions = new Size(int.Parse(widthAndHeight[0]), 
                int.Parse(widthAndHeight[1]));
            }
        }
        /// <summary>
        /// Gets the Video Extentions that belong to itag
        /// </summary>
        public string VideoExtentions { get; private set; }
        /// <summary>
        /// Gets the Video Dimensions that belong to itag
        /// </summary>
        public Size VideoDimensions { get; private set; }
    }

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: Resolution displayed incorectly in Quality setting Pin
CircleDock18-Feb-13 4:29
memberCircleDock18-Feb-13 4:29 
GeneralMy vote of 5 Pin
Johann Krenn16-Feb-13 0:08
memberJohann Krenn16-Feb-13 0:08 
QuestionMy vote of 5 Pin
bandi.ramesh15-Feb-13 21:46
memberbandi.ramesh15-Feb-13 21:46 
QuestionMy solution for the constant YouTube changes. Pin
TheFigmo15-Feb-13 6:20
memberTheFigmo15-Feb-13 6:20 
AnswerRe: My solution for the constant YouTube changes. Pin
CircleDock15-Feb-13 8:12
memberCircleDock15-Feb-13 8:12 
GeneralRe: My solution for the constant YouTube changes. Pin
TheFigmo15-Feb-13 8:42
memberTheFigmo15-Feb-13 8:42 
GeneralRe: My solution for the constant YouTube changes. Pin
CircleDock15-Feb-13 23:37
memberCircleDock15-Feb-13 23:37 
GeneralRe: My solution for the constant YouTube changes. Pin
TheFigmo16-Feb-13 4:20
memberTheFigmo16-Feb-13 4:20 
GeneralRe: My solution for the constant YouTube changes. Pin
Riz Thon25-Feb-13 18:02
memberRiz Thon25-Feb-13 18:02 
QuestionYouTubes' new changes break this code Pin
CircleDock14-Feb-13 8:47
memberCircleDock14-Feb-13 8:47 
AnswerRe: YouTubes' new changes break this code Pin
akramKamal14-Feb-13 10:10
memberakramKamal14-Feb-13 10:10 
AnswerRe: YouTubes' new changes break this code [modified] Pin
CircleDock14-Feb-13 21:50
memberCircleDock14-Feb-13 21:50 
QuestionHow to get filesize ? Pin
jeffingeorge31-Jan-13 1:13
memberjeffingeorge31-Jan-13 1:13 
QuestionTargetInvocationException was unhandled Pin
Member 978351625-Jan-13 8:23
memberMember 978351625-Jan-13 8:23 
Program is crashing when I click get button very often.

System.Reflection.TargetInvocationException was unhandled
  Message=Obiekt docelowy wywołania zgłosił wyjątek.
  Source=mscorlib
  StackTrace:
       w System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
       w System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
       w System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
       w System.Delegate.DynamicInvokeImpl(Object[] args)
       w System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme)
       w System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
       w System.Threading.ExecutionContext.runTryCode(Object userData)
       w System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
       w System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
       w System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       w System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)
       w System.Windows.Forms.Control.InvokeMarshaledCallbacks()
       w System.Windows.Forms.Control.WndProc(Message& m)
       w System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       w System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       w System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       w System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       w System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       w System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       w System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       w System.Windows.Forms.Application.Run(Form mainForm)
       w YouTube_Downloader.Program.Main() w C:\YouTube Downloader\Program.cs:wiersz 19
       w System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       w System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       w Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       w System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       w System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       w System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.NullReferenceException
       Message=Odwołanie do obiektu nie zostało ustawione na wystąpienie obiektu.
       Source=YouTube Downloader
       StackTrace:
            w YouTube_Downloader.mainForm.backgroundWorker1_RunWorkerCompleted(Object sender, RunWorkerCompletedEventArgs e) w C:\YouTube Downloader\mainForm.cs:wiersz 81
            w System.ComponentModel.BackgroundWorker.OnRunWorkerCompleted(RunWorkerCompletedEventArgs e)
            w System.ComponentModel.BackgroundWorker.AsyncOperationCompleted(Object arg)
       InnerException: 

AnswerRe: TargetInvocationException was unhandled Pin
TheFigmo13-Feb-13 17:19
memberTheFigmo13-Feb-13 17:19 
AnswerRe: TargetInvocationException was unhandled Pin
CircleDock14-Feb-13 22:14
memberCircleDock14-Feb-13 22:14 
SuggestionThe code works, but you need to send User Agent while requesting getSize Pin
nantcom12-Jan-13 23:01
membernantcom12-Jan-13 23:01 
GeneralRe: The code works, but you need to send User Agent while requesting getSize Pin
nantcom13-Jan-13 0:30
membernantcom13-Jan-13 0:30 
GeneralRe: The code works, but you need to send User Agent while requesting getSize Pin
akramKamal13-Jan-13 1:39
memberakramKamal13-Jan-13 1:39 
GeneralRe: The code works, but you need to send User Agent while requesting getSize Pin
Vincenzo Lo Palo9-Feb-13 6:37
memberVincenzo Lo Palo9-Feb-13 6:37 
QuestionLink error Pin
bzsolt916-Jan-13 18:04
memberbzsolt916-Jan-13 18:04 
AnswerRe: Link error Pin
CircleDock6-Jan-13 20:09
memberCircleDock6-Jan-13 20:09 
GeneralMy vote of 4 Pin
Jai Mallesh1-Jan-13 1:45
memberJai Mallesh1-Jan-13 1:45 
GeneralRe: My vote of 4 Pin
akramKamal1-Jan-13 4:32
memberakramKamal1-Jan-13 4:32 
QuestionRe: My vote of 4 Pin
Empire44310-Feb-13 10:36
memberEmpire44310-Feb-13 10:36 
QuestionNew Version Posted Pin
akramKamal28-Dec-12 11:49
memberakramKamal28-Dec-12 11:49 
AnswerRe: New Version Posted [modified] Pin
DiabloPB29-Dec-12 1:00
memberDiabloPB29-Dec-12 1:00 
NewsRe: New Version Posted Pin
Motaz Alnuweiri29-Dec-12 4:51
memberMotaz Alnuweiri29-Dec-12 4:51 
GeneralRe: New Version Posted Pin
DiabloPB29-Dec-12 6:06
memberDiabloPB29-Dec-12 6:06 
GeneralRe: New Version Posted Pin
akramKamal29-Dec-12 4:57
memberakramKamal29-Dec-12 4:57 
QuestionNot working Pin
kabila28-Dec-12 5:42
memberkabila28-Dec-12 5:42 
BugDEC 25 version not working for me Pin
TheFigmo27-Dec-12 11:01
memberTheFigmo27-Dec-12 11:01 
GeneralRe: DEC 25 version not working for me Pin
DiabloPB27-Dec-12 12:26
memberDiabloPB27-Dec-12 12:26 
GeneralRe: DEC 25 version not working for me Pin
CircleDock27-Dec-12 20:21
memberCircleDock27-Dec-12 20:21 
GeneralRe: DEC 25 version not working for me Pin
TheFigmo28-Dec-12 7:26
memberTheFigmo28-Dec-12 7:26 
GeneralRe: DEC 25 version not working for me Pin
CircleDock28-Dec-12 8:47
memberCircleDock28-Dec-12 8:47 
GeneralRe: DEC 25 version not working for me Pin
TheFigmo28-Dec-12 9:21
memberTheFigmo28-Dec-12 9:21 
QuestionMP3 Pin
maltra26-Dec-12 9:54
membermaltra26-Dec-12 9:54 
AnswerRe: MP3 Pin
CircleDock27-Dec-12 20:39
memberCircleDock27-Dec-12 20:39 
Questionitag values corrected - but a problem remains... [modified] Pin
CircleDock24-Dec-12 22:40
memberCircleDock24-Dec-12 22:40 
AnswerRe: itag values corrected - but a problem remains... Pin
akramKamal25-Dec-12 9:57
memberakramKamal25-Dec-12 9:57 
GeneralRe: itag values corrected - but a problem remains... Pin
Motaz Alnuweiri26-Dec-12 1:19
memberMotaz Alnuweiri26-Dec-12 1:19 
GeneralRe: itag values corrected - but a problem remains... Pin
akramKamal28-Dec-12 11:53
memberakramKamal28-Dec-12 11:53 
GeneralRe: itag values corrected - but a problem remains... Pin
CircleDock26-Dec-12 6:13
memberCircleDock26-Dec-12 6:13 
Questionit doesn`t work again Pin
WerWolf_Victor24-Dec-12 11:42
memberWerWolf_Victor24-Dec-12 11:42 
AnswerRe: it doesn`t work again Pin
akramKamal24-Dec-12 13:07
memberakramKamal24-Dec-12 13:07 
GeneralRe: it doesn`t work again Pin
WerWolf_Victor24-Dec-12 23:08
memberWerWolf_Victor24-Dec-12 23:08 
GeneralRe: it doesn`t work again Pin
akramKamal25-Dec-12 9:57
memberakramKamal25-Dec-12 9:57 
GeneralRe: it doesn`t work again Pin
Haloniels19975-Jan-13 5:59
memberHaloniels19975-Jan-13 5:59 
QuestionIt has stopped working Pin
Member 892943719-Dec-12 5:20
memberMember 892943719-Dec-12 5:20 

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
Web03 | 2.8.150428.2 | Last Updated 8 Feb 2015
Article Copyright 2014 by akramKamal
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid