Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to Create a Youtube Downloader using C#

Youtube downloader is a popular tool used to download video and audio content from the internet. In this article were gonna see how to build one using .Net.

Youtube downloader is a popular tool used to download video and audio content from the internet. This document is specially prepared for those developers who are interested in developing client applications which can interact with youtube over the internet. It is assumed while preparing this document that the reader is well versed with the .NET framework and the C# programming language. In this document, we will see how to develop an application using the C# programming language. This sample program will be used to download videos from YouTube.

Before going anywhere, it is very much important to know the details of the YouTube Downloader.? YouTube Downloader is a software which is used to download video and audio contents from different internet websites e.g. YouTube, Facebook, Google Video, Yahoo Video, and many others. The YouTube downloader also converts these downloaded files to other video formats. The program is written in a very simple and easy manner. Also, it is very easy to execute the program. We just need to specify the URL for the video which we want to download and then hit the Ok button.

This program also allows users to convert downloaded videos for Ipod, PSP, Cell Phone, Iphone, Windows Media, XVid and MP3. In order to execute this application, we have certain requirements which we must ensure to have on the computer on which we want to run this application. These requirements are under:

  • Intel Pentium 233 Mhz (or equivalent processor, such as AMD) or better
  • Windows XP/Vista/7/8
  • Internet Explorer 6.0 or higher
  • 64 MB of RAM
  • Adobe Flash Player 9+

We will be using the C# programming language here to develop a sample YouTube downloader application. The code used for developing this application is a very simple and easy to understand to any developer. This code can easily be integrated with their ongoing solutions or projects. Here, in this article, the third party library is not used for doing the task. The only thing that needs to be done is to take two .cs files and then finally integrate them into the project.

The Youtube Data API

The YouTube Data API enables us to develop applications to retrieve and update YouTube content in the form of data feeds. It works in the same way the Google Data API works. The client side application always take help of the YouTube Data API to fetch different components like video feeds, responses, comments, playlists, along with the query for different videos. This query should match a particular criterion. The data API can also be used to execute authenticated requests to update this information and to upload the new video content to the site.

Authentication

The client library (.NET based) is used to retrieve public feeds over the internet or even to execute the authenticated operations. All the public feeds exist in read-only mode. They do not require any authentication. On the other hand, authenticated operations, does the retrieval of private feeds along with the basic write, upload, update and delete operations. A user needs to register and get the developer key. This developer key will allow the user to execute all authenticated operations.

We can use either of the following authentication mechanisms to authenticate requests -

  • AuthSub proxy authentication
  • Client based username/password authentication.

In order to execute any operation by using the YouTube API, we need to create a YouTubeRequestSettings object. This object mentions the authentication information and also scheme which is to be used. Using this object, we then create a YouTubeRequest object. This object is used to actually perform the operations. It must be noted that if we do not specify the authentication information while creating the YouTubeRequestSettings object, then we will be allowed to use and perform operations only on those YouTubeRequest objects, which do not require authentication.

Developing sample program

Let us have a look at some sample programs mentioned below.

Shows the snapshot of the YouTube downloader

Figure 1. Shows the snapshot of the YouTube downloader.

In order to develop the YouTube downloader application, we are writing two main classes. These two classes are as follows:

  • YouTubeVideoQuality Class: This class is used for describing the video.
  • YouTubeDownloader Class: This class is used for downloading the video.

Now we have to write down the code in two (.cs) files. One file is mainForm.cs, where the main code of the first screen is written. The following code is written for that purpose. After that the second screen is written in downLoad.cs file. At the time of creating this project, user needs to open visual studio 2010 through C# project and create the following file.

The following file, mainForm.cs is the first program in the project. This main class is required to design the page. This class also sets the file types that are in the application. Here we also handle some exceptional conditions which are capable enough to check if any error is occurring in the page or not.

Listing 1. The downloader class

// Libraries used in this class:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
using System.Net;
using System.IO;

namespace YouTube_Getter
{
    public partial class mainForm : Form
    {
        //internal mainForm()
        public mainForm()
        {
            InitializeComponent();
        }
        private byte[] downloadedDataStream;
        private Video_Downloader_DLL.VideoDownloader downloader = new Video_Downloader_DLL.VideoDownloader();
        private void Button1_Operation(object sender, System.EventArgs e)
        {
            string videoHeader = "";
            //string thumbnailurl = "";
            string outputStr = "";
            string fileinputurl = TextBox1.Text;
            downloader.GetvideoHeader(fileinputurl, ref videoHeader);
            System.String tempVar = "";
            System.Int32 tempVar2 = 0;
            downloader.MakeDownloadURL(fileinputurl, ref outputStr, ref tempVar, ref tempVar2);
            //downloader.GetPreviewThumbnail(fileinputurl, ref thumbnailurl);
            OutLink.Text = (videoHeader);
            LinkText.Text = (outputStr);
            //PicImage.Text = (thumbnailurl);
            MessageBox.Show("To Download " + videoHeader + Environment.NewLine + "Please click Download now, When finished Downloading select Save To File");
        }
        private void downloadData(string url)
        {
            progressBar1.Value = 0;
            downloadedDataStream = new byte[0];
            try
            {
                //Optional
                this.Text = "Connecting...";
                Application.DoEvents();
                //Get a data stream from the url
                WebRequest req = WebRequest.Create(url);
                WebResponse response = req.GetResponse();
                Stream stream = response.GetResponseStream();
                //Download in chuncks
                byte[] buffer = new byte[1024];
                //Get Total Size
                int dataLength = (int)response.ContentLength;
                //With the total data we can set up our progress indicators
                progressBar1.Maximum = dataLength;
                lbProgress.Text = "0/" + dataLength.ToString();

                this.Text = "Downloading...";
                Application.DoEvents();

                //Download to memory
                //Note: adjust the streams here to download directly to the hard drive
                MemoryStream memStream = new MemoryStream();
                while (true)
                {
                    //Try to read the data
                    int bytesRead = stream.Read(buffer, 0, buffer.Length);

                    if (bytesRead == 0)
                    {
                        //Finished downloading
                        progressBar1.Value = progressBar1.Maximum;
                        lbProgress.Text = dataLength.ToString() + "/" + dataLength.ToString();

                        Application.DoEvents();
                        break;
                    }
                    else
                    {
                        //Write the downloaded data
                        memStream.Write(buffer, 0, bytesRead);

                        //Update the progress bar
                        if (progressBar1.Value + bytesRead <= progressBar1.Maximum)
                        {
                            progressBar1.Value += bytesRead;
                            lbProgress.Text = progressBar1.Value.ToString() + "/" + dataLength.ToString();

                            progressBar1.Refresh();
                            Application.DoEvents();
                        }
                    }
                }

                //Convert the downloaded stream to a byte array
                downloadedDataStream = memStream.ToArray();

                //Clean up
                stream.Close();
                memStream.Close();
            }
            catch (Exception)
            {
                //May not be connected to the internet
                //Or the URL might not exist
                MessageBox.Show("There was an error accessing the URL.");
            }

            txtData.Text = downloadedDataStream.Length.ToString();
            this.Text = "YT Snatcher";
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            downloadData(LinkText.Text);

            //Get the last part of the url, ie the file name
            if (downloadedDataStream != null && downloadedDataStream.Length != 0)
            {
                string ytdata = OutLink.Text;
                string urlName = LinkText.Text;
                if (urlName.EndsWith("/"))
                    urlName = urlName.Substring(0, urlName.Length - 1); //Chop off the last '/'

                urlName = urlName.Substring(urlName.LastIndexOf('/') + 1);

                saveDiag1.FileName = ytdata + ".flv";
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (downloadedDataStream != null && downloadedDataStream.Length != 0)
            {
                if (saveDiag1.ShowDialog() == DialogResult.OK)
                {
                    this.Text = "Saving your file ...";
                    Application.DoEvents();

                    //Write the bytes to a file
                    FileStream newFile = new FileStream(saveDiag1.FileName, FileMode.Create);
                    newFile.Write(downloadedDataStream, 0, downloadedDataStream.Length);
                    newFile.Close();

                    this.Text = "Download Data";
                    MessageBox.Show("Saved the file Successfully");
                }
            }
            else
                MessageBox.Show("No File was Downloaded !");
        }
    }
}    

Listing 2. The mainForm class

// Libraries used in this class:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;

namespace YouTube_Getter
{
	
	public partial class mainForm : System.Windows.Forms.Form
	{

		//Form overrides dispose to clean up the component list.
		[System.Diagnostics.DebuggerNonUserCODE()]
		protected override void Dispose(bool disposeWindow)
		{
			try
			{
				if (disposeWindow && components != null)
				{
					components.Dispose();
				}
			}
			finally
			{
				base.Dispose(disposeWindow);
			}
		}

		//Required by the Windows Form Designer
		private System.ComponentModel.IContainer components;

		//NOTE: The following procedure is required by the Windows Form Designer
		//It can be modified using the Windows Form Designer.  
		//Do not modify it using the code editor.
		[System.Diagnostics.DebuggerStepThrough()]
		private void InitializeComponent()
		{
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(mainForm));
            this.OutLink = new System.Windows.Forms.TextBox();
            this.Button1 = new System.Windows.Forms.Button();
            this.TextBox1 = new System.Windows.Forms.TextBox();
            this.LinkText = new System.Windows.Forms.TextBox();
            this.txtData = new System.Windows.Forms.TextBox();
            this.label4 = new System.Windows.Forms.Label();
            this.progressBar1 = new System.Windows.Forms.ProgressBar();
            this.label5 = new System.Windows.Forms.Label();
            this.label6 = new System.Windows.Forms.Label();
            this.lbProgress = new System.Windows.Forms.Label();
            this.btnDownload = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.label7 = new System.Windows.Forms.Label();
            this.saveDiag1 = new System.Windows.Forms.SaveFileDialog();
            this.SuspendLayout();
            // 
            // OutLink
            // 
            this.OutLink.Location = new System.Drawing.Point(278, 32);
            this.OutLink.Name = "OutLink";
            this.OutLink.Size = new System.Drawing.Size(289, 20);
            this.OutLink.TabIndex = 0;
            this.OutLink.Visible = false;
            // 
            // Button1
            // 
            this.Button1.BackColor = System.Drawing.SystemColors.Control;
            this.Button1.Location = new System.Drawing.Point(79, 74);
            this.Button1.Name = "Button1";
            this.Button1.Size = new System.Drawing.Size(75, 23);
            this.Button1.TabIndex = 1;
            this.Button1.Text = "Get File Info";
            this.Button1.UseVisualStyleBackColor = false;
            this.Button1.Click += new System.EventHandler(this.Button1_Click);
            // 
            // TextBox1
            // 
            this.TextBox1.Location = new System.Drawing.Point(144, 5);
            this.TextBox1.Name = "TextBox1";
            this.TextBox1.Size = new System.Drawing.Size(423, 20);
            this.TextBox1.TabIndex = 2;
            // 
            // LinkText
            // 
            this.LinkText.Location = new System.Drawing.Point(12, 32);
            this.LinkText.Name = "LinkText";
            this.LinkText.Size = new System.Drawing.Size(240, 20);
            this.LinkText.TabIndex = 4;
            this.LinkText.Visible = false;
            // 
            // txtData
            // 
            this.txtData.BackColor = System.Drawing.SystemColors.Control;
            this.txtData.Location = new System.Drawing.Point(123, 116);
            this.txtData.Name = "txtData";
            this.txtData.Size = new System.Drawing.Size(444, 20);
            this.txtData.TabIndex = 12;
            this.txtData.Text = "0";
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.BackColor = System.Drawing.Color.Gold;
            this.label4.Location = new System.Drawing.Point(12, 5);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(123, 13);
            this.label4.TabIndex = 13;
            this.label4.Text = "Put the YouTube Url Here";
            // 
            // progressBar1
            // 
            this.progressBar1.BackColor = System.Drawing.SystemColors.Control;
            this.progressBar1.ForeColor = System.Drawing.Color.LawnGreen;
            this.progressBar1.Location = new System.Drawing.Point(123, 153);
            this.progressBar1.Name = "progressBar1";
            this.progressBar1.Size = new System.Drawing.Size(311, 23);
            this.progressBar1.TabIndex = 14;
            // 
            // label5
            // 
            this.label5.AutoSize = true;
            this.label5.BackColor = System.Drawing.Color.Gold;
            this.label5.Location = new System.Drawing.Point(12, 153);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(67, 13);
            this.label5.TabIndex = 15;
            this.label5.Text = "PROGRESS";
            // 
            // label6
            // 
            this.label6.AutoSize = true;
            this.label6.BackColor = System.Drawing.Color.Gold;
            this.label6.Location = new System.Drawing.Point(9, 119);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(101, 13);
            this.label6.TabIndex = 16;
            this.label6.Text = "DATA IS IN THE MEMORY";
            // 
            // lbProgress
            // 
            this.lbProgress.AutoSize = true;
            this.lbProgress.Location = new System.Drawing.Point(440, 159);
            this.lbProgress.Name = "lbProgress";
            this.lbProgress.Size = new System.Drawing.Size(24, 13);
            this.lbProgress.TabIndex = 17;
            this.lbProgress.Text = "0/0";
            // 
            // btnDownload
            // 
            this.btnDownload.BackColor = System.Drawing.SystemColors.Control;
            this.btnDownload.Location = new System.Drawing.Point(315, 69);
            this.btnDownload.Name = "btnDownload";
            this.btnDownload.Size = new System.Drawing.Size(119, 23);
            this.btnDownload.TabIndex = 18;
            this.btnDownload.Text = "START DOWNLOAD NOW ...";
            this.btnDownload.UseVisualStyleBackColor = false;
            this.btnDownload.Click += new System.EventHandler(this.btnDownload_Click);
            // 
            // button2
            // 
            this.button2.BackColor = System.Drawing.SystemColors.Control;
            this.button2.Location = new System.Drawing.Point(462, 69);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(105, 23);
            this.button2.TabIndex = 19;
            this.button2.Text = "SAVE IN TO FILE";
            this.button2.UseVisualStyleBackColor = false;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            // 
            // label7
            // 
            this.label7.AutoSize = true;
            this.label7.BackColor = System.Drawing.Color.Gold;
            this.label7.Location = new System.Drawing.Point(12, 79);
            this.label7.Name = "label7";
            this.label7.Size = new System.Drawing.Size(44, 13);
            this.label7.TabIndex = 20;
            this.label7.Text = "STEP 1";
            // 
            // mainForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.Color.DarkSlateGray;
            this.ClientSize = new System.Drawing.Size(579, 199);
            this.Controls.Add(this.label7);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.btnDownload);
            this.Controls.Add(this.lbProgress);
            this.Controls.Add(this.label6);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.progressBar1);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.txtData);
            this.Controls.Add(this.LinkText);
            this.Controls.Add(this.TextBox1);
            this.Controls.Add(this.Button1);
            this.Controls.Add(this.OutLink);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "mainForm";
            this.Text = "YOUTUBE DOWNLOADER - Downloads files from you tube";
            this.ResumeLayout(false);
            this.PerformLayout();
		}
		internal System.Windows.Forms.TextBox OutLink;
		internal System.Windows.Forms.Button Button1;
        internal System.Windows.Forms.TextBox TextBox1;
        internal System.Windows.Forms.TextBox LinkText;
		internal System.Windows.Forms.TextBox txtData;
        private Label label4;
        private ProgressBar progressBar1;
        private Label label5;
        private Label label6;
        private Label lbProgress;
        private Button btnDownload;
        private Button button2;
        private Label label7;
        private SaveFileDialog saveDiag1;
	}
} //end of root namespace

As we see in the above code snippet, our application works along with the following steps -

  • Step 1 - We first prepare the downloader which is required to download the video.
  • Step 2 - We now have the button 1 click event. This event triggers the DLL. At this point, the DLL will give us the link of the download and also the name of the video file. The two textboxes are set to non visible (visible = false). We will need this information in the back in order to fetch the download link of the video which is to be downloaded and also to get the file name. The file name is required to put it in the save as on the savefiledialog and also in the message box which shows that the file is being downloaded.
  • Step 3 - Now that we have the information about the download from the DLL, let us start working on setting up the download. Here we initialize our progress bar. This progress bar refreshes and adjusts itself as per quantity of the bytes which are being downloaded. It works in the following steps -
    • First it makes a web request
    • If the web request is successful, which means that the download file is found, then it starts downloading the file in chunks of bytes over a byte buffer using the memory stream.
    • These bytes are then converted to a byte array.
    • If the requested URL fails, which means that the download is unsuccessful since the download link was not found, then an appropriate message box is shown to the user mentioning that there was an error accessing the URL.
  • Step 4 - Once we have our download web request ready, we then add the download button event. This starts downloading the file corresponding to the URL which is mentioned in the LinkText text box. The string ytdata is the video file title which the DLL generated earlier. Here, we have the ytdata string set as the savefiledialogs filename to save to and have it set to add the extension .flv. We can simply rename the flv file to wmv extension, the data stays the same and wmp player can play it well.
  • Step 5 - Now that we have the data downloaded, it is in the memory stream. We now need to save this into a file on the click event of the save button. This brings up the save file dialog with the file to save to as the video title + .flv. We can change to mp4 only if the original file was mp4. If the original file wasn't and it was saved as mp4, we just need to rename it back to .flv
  • Step 6 - We now have the downloaded YouTube video stored on our computer. We can view anytime we want.

Retrieve and Search for videos

  • The Youtube data API allows us to search and retrieve video and audio files based on the following categories -
    • Country or region specific contents
    • Language specific contents

The URL for a Country/Region/Language specific feeds should be as under -

http://gdata.youtube.com/feeds/api/standardfeeds/localeID/most_popular_CATEGORY_NAME

For example, if we need to get the list of comedy shows in 'Italian' language, our URL should be as -

http://gdata.youtube.com/feeds/api/standardfeeds/IT/most_popular_Comedy

The Youtube data API allows us to list all the feeds which are uploaded by a specific user. The URL format could be as followsunder -

http://gdata.youtube.com/feeds/api/users/username/uploads

We can also fetch a specific video by providing the unique identification of that video. The URL format should be -

http://gdata.youtube.com/feeds/api/users/username/uploads/VIDEO_ID

Given below is the list of queries which can be appended in the URL as a query parameter. The URL format could be -

http://gdata.youtube.com/feeds/api/videos?q=keyword&safeSearch=none&orderby=viewCount

Parameter List -

  • Author - Used to set the author of the content
  • Format - Used to specify the video format.
  • Location - Used to specify the geographic coordinates in terms of latitude and longitude.
  • Number to fetch - Used to specify the maximum number of rows to be fetched.
  • Order by - Used to get the output in a specified order.
  • Uploaded by - Used to specify the name of the user who has uploaded the content.

Important Features of Youtube Data API

Let us talk about some of the features which the Youtube Data API comes with -

  • We can provide ratings on a scale of 1 - 5 for every content, where 5 is the best.
  • We can add comments on the video contents.
  • We can set flags on the contents.
  • We can mark some of the contents as favorites which we can refer soon.

Conclusion

In this article, I have talked about the Youtube downloader and how it operates. I have talked about the basics of the Youtube downloader API and also its features. Let us conclude our discussion in the form of following bullets -

  • YouTube Downloader is a software which is used to download video and audio contents from different internet websites.
  • The YouTube downloader is also used to convert these downloaded files to other video formats.
  • The YouTube Data API allows us to develop applications to retrieve and update YouTube content in the form of data feeds.
  • The Youtube Data API works in the same way the Google Data API works.
  • The Youtube Data API has an built-in authentication mechanism. User needs to register and get the key in order to start accessing the youtube content. The authentication mechanism is based on -
    • AuthSub based
    • Client Based
  • Any operation using Youtube Data API revolves around the YouTubeRequestSettings.
  • The Youtube data API allows us to append parameters in the query. The most commonly used parameters are - Author, Format, Location, Number to fetch, Order by, Uploaded by etc.
  • Youtube data API comes with array of features. The most important ones are listed above.

I believe now you have got an idea of what the youtube downloader is and how it operates along with its features. We can develop the client program to use the data API using other programming languages e.g. Java etc. Good reading!!



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login