How to download YouTube Videos using .NET - Blogs
X
15May

How to download YouTube Videos using .NET

Are you interested in downloading YouTube Videos?
Want to download YouTube Videos in device specific formats?
Need to have some fun while coding on interesting Stuff?

Yes, then you are at the right place! In this blog I am going to show you how we can download the Videos from YouTube URL in different formats. You can download the video from YouTube URL in these formats: .Mp4, .Flv, .3Gp, .WebM

Each YouTube video URL has a video id, which is appended to the URL as a query string. The name of the query string to get the video id is v. The typical YouTube video URL looks like this:

http://www.youtube.com/watch?v=aqkkByP8RDM

In the above URL, aqkkByP8RDM is the video id. To download the video from this URL, first we need to get some more detailed information about this video which includes video formats and video file URLs. The below URL can be helpful to get the more details about video:

http://www.youtube.com/get_video_info?video_id=aqkkByP8RDM

The above URL not only gives us the information about video formats and URLs, it also includes video title, description, viewers count, etc. 

All we need is extract the required information from the above URL and do download video file whichever the format you need. Here I am going to show you the step by step procedure to extract video formats and video file URLs for download a video.

 

For demonstration I have used the ASP.NET with C# as a language. You can use any other .NET language which ever you prefer. I have designed a small UI in ASP.NET which accepts the YouTube video URL from user:
 

<div>
  <
table>
   <
tr>
    <
td>
     YouTube URL:
    td>
    <
td>
     <
asp:TextBox ID="txtYouTubeURL" runat="server" Text="" Width="450" />
    td>
   tr>
   <
tr>
    <
td>
    td>
    <
td>
     <
asp:Button ID="btnProcess" Text="Process" runat="server" OnClick="btnProcess_Click"
       Width
="100" />
    td>
   tr>
   <
tr>
    <
td>
      <
asp:DropDownList ID="ddlVideoFormats" runat="server" Visible="false">          asp:DropDownList>
    td>
    <
td>
      <
asp:Button ID="btnDownload" Text="Download" runat="server" OnClick="btnDownload_Click" Width="100" Visible="false" />
    td>
   tr>
 table>
 <
br />
 <
asp:Label ID="lblMessage" Text="" runat="server" />
div>

 

I have also added a button called Process button. The process button will get the detailed information about requested URL from YouTube and extracts the video formats and video URLs to download the video.

I am also showing these video formats and URLs in a DropDownList control, so that user can download a video in his preferred format.

The below code is used to get detailed information of YouTube URL and extracting the needed information to download a video:

protected void btnProcess_Click(object sender, EventArgs e)
{
  try
  {
    Uri videoUri = new Uri(txtYouTubeURL.Text);
    string videoID = HttpUtility.ParseQueryString(videoUri.Query).Get("v");
    string videoInfoUrl = "http://www.youtube.com/get_video_info?video_id=" + videoID;

 

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(videoInfoUrl);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

 

    Stream responseStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));

 

    string videoInfo = HttpUtility.HtmlDecode(reader.ReadToEnd());

 

    NameValueCollection videoParams = HttpUtility.ParseQueryString(videoInfo);

 

    if (videoParams["reason"] != null)
    {
      lblMessage.Text = videoParams["reason"];
      return;
    }

 

    string[] videoURLs = videoParams["url_encoded_fmt_stream_map"].Split(',');

 

    foreach (string vURL in videoURLs)
    {
      string sURL = HttpUtility.HtmlDecode(vURL);

 

      NameValueCollection urlParams = HttpUtility.ParseQueryString(sURL);
      string videoFormat = HttpUtility.HtmlDecode(urlParams["type"]);

 

      sURL = HttpUtility.HtmlDecode(urlParams["url"]);
      sURL += "&signature=" + HttpUtility.HtmlDecode(urlParams["sig"]);
      sURL += "&type=" + videoFormat;
      sURL += "&title=" + HttpUtility.HtmlDecode(videoParams["title"]);

 

      videoFormat = urlParams["quality"] + " - " + videoFormat.Split(';')[0].Split('/')[1];

 

      ddlVideoFormats.Items.Add(new ListItem(videoFormat, sURL));
    }

 

    btnProcess.Enabled = false;
    ddlVideoFormats.Visible = true;
    btnDownload.Visible = true;
    lblMessage.Text = string.Empty;
  }
  catch (Exception ex)
  {
    lblMessage.Text = ex.Message;
    lblMessage.ForeColor = Color.Red;
    return;
  }
}

 

private void Completed(object sender, AsyncCompletedEventArgs e)
{
  lblMessage.Text = "Video downloaded on: " + DateTime.Now.ToString();
  lblMessage.ForeColor = Color.Green;
}

When you take a deep look at detailed information of YouTube video URL, you can find url_encoded_fmt_stream_map parameter has many video URLs and each video URL is separated by comma (,) as a delimiter. And, each URL has the video format and quality of it.

Quality parameter tells us the size of video like, small, medium, large, high definition (HD)

Once you extract the direct video URLs from the parameter, you are ready to download it. Below code is used to download the video (not only video, it can be used to for any file download) from direct URL:

protected void btnDownload_Click(object sender, EventArgs e)
{
  try
  {
    string sURL = ddlVideoFormats.SelectedValue;

 

    if (string.IsNullOrEmpty(sURL))
    {
      lblMessage.Text = "Unable to locate the Video.";
      return;
    }

 

    NameValueCollection urlParams = HttpUtility.ParseQueryString(sURL);

 

    string videoTitle = urlParams["title"] + " " + ddlVideoFormats.SelectedItem.Text;
    string videoFormt = HttpUtility.HtmlDecode(urlParams["type"]);
    videoFormt = videoFormt.Split(';')[0].Split('/')[1];

 

    string downloadPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
    string sFilePath = string.Format(Path.Combine(downloadPath, "Downloads\\{0}.{1}"),    videoTitle, videoFormt);

 

    WebClient webClient = new WebClient();
    webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
    webClient.DownloadFileAsync(new Uri(sURL), sFilePath);
  }
  catch (Exception ex)
  {
    lblMessage.Text = ex.Message;
    lblMessage.ForeColor = Color.Red;
    return;
  }
}

The above code will downloads the requested video using WebClient class and place it into Downloads folder of your machine.

Below is the screenshot of rendered UI on my webpage and it also contains the processed video formats of sample YouTube URL.

YouTube

Happy Coding…!

 

Related

Deploy .NET application on IIS using GitHub actions

In this blog I will be showing how to deploy a .net application on IIS server (self-hosted runner). ...

Read More >

What are Frames? How to handle frames in Selenium WebDriver with C#?

IFrame (FullForm: Inline Frame) is an HTML document that is included in another HTML document and is...

Read More >

What is Synchronization? Handling Synchronization in Selenium WebDriver using C#:

Synchronization meaning: when two or more components involved to perform any action, we expect these...

Read More >

Sending Test reports by Email using Office 365, Gmail

Wouldn’t it be great if Test Report are sent automatically across team as soon the Test Execut...

Read More >

Token Based Authentication for Web API's

Securing ASP.NET Web API using Custom Token Based AuthenticationProviding a security to the Web API&...

Read More >

Custom Control in WPF

File Upload Custom Control in WPFThis article is about Custom control in WPF, Custom controls are al...

Read More >

ASP.NET: Audit Trail Implementation using Entity Framework

When you are working with certain projects which involves the Customer records, you might need to tr...

Read More >

Create Restful service using Web API

What is Asp.Net Web API?Asp.Net Web API is a framework for building HTTP services that can be consum...

Read More >

Dependency Injection on SignalR

                &nbs...

Read More >

Create custom project templates in Visual Studio

Visual studio installation comes with the various predefined project templates, and we can use one o...

Read More >

Share

Try DevOpSmartBoard Ultimate complete Azure DevOps End-to end reporting tool

Sign Up

  • Recent
  • Popular
  • Tag
Monthly Archive
Subscribe
Name

Text/HTML
Contact Us
  • *
  • *