Download YouTube Videos using ASP.NET

Many people used to search for tools/installers to download videos from YouTube. If some of them are available as free, but few are paid ones with limited download size in their evaluation. With the help of .NET framework, we can build our own applications to download full length of videos.


There might be couple of ways to do this, but here I am going to share my ideas on this using ASP.NET. The same can be easily migrated to either C#.NET or VB.NET. Here are the step by step procedure to be followed to download the YouTube videos:

Step1: Add an aspx page to you current project. In case of mine it is, YouTube.aspx

Step2: In the webform, add the async property to Page attribute. This will informs to ASP.NET engine, the page have async methods.

<%@ Page Language="C#" Async="true" AutoEventWireup="true"

Step3: Add a TextBox and Button controls to webform. TextBox is for accepting YouTube Video URL and Button event contains the core logic for downloading video to target path. (In my case, I am downloading videos to system downloads folder).
<span>Enter YouTube URL:</span>
<b r />
<asp:TextBox ID="txtYouTubeURL" runat="server" Text="" Width="450" />
<b r />
<asp:Button ID="btnDownload" Text="Download" runat="server" OnClick="btnDownload_Click" />
<b r />
<b r />
<asp:Label ID="lblMessage" Text="" runat="server" />
Step4: YouTube URL's are not an actual video download URLs. We need to track all the URLs from the Page Source. Among all the URLs, get one of the URL having query string with type as 'video/mp4'. At the same time get Video title from Page Source itself. Once we are ready with Video URL and Title, make a request to server to download the video file from YouTube.
    protected void btnDownload_Click(object sender, EventArgs e)
    {
        DownloadYouTubeVideo();
    }
        private void DownloadYouTubeVideo()
        {
            try
            {
                string sURL = txtYouTubeURL.Text.Trim();
                bool isDownloaded = false;

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

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

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

                List<Uri> urls = GetVideoDownloadUrls(pageSource);

                string videoTitle = HttpUtility.HtmlDecode(GetVideoTitle(pageSource));                

                foreach (Uri url in urls)
                {
                    NameValueCollection queryValues = HttpUtility.ParseQueryString(url.OriginalString);

                    if (queryValues["type"].ToString().StartsWith("video/mp4"))
                    {
                        string downloadPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
                        string sFilePath = string.Format(Path.Combine(downloadPath, "Downloads\\{0}.mp4"), videoTitle);

                        WebClient client = new WebClient();
                        client.DownloadFileCompleted += client_DownloadFileCompleted;                        
                        client.DownloadFileAsync(url, sFilePath);
                        isDownloaded = true;

                        break;
                    }
                }

                if (urls.Count == 0 || !isDownloaded)
                {
                    lblMessage.Text = "Unable to locate the Video.";
                    return;
                }
            }
            catch (Exception e)
            {
                lblMessage.Text = "An error occurred while downloading video: " + e.Message;
            }
        }
        private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            lblMessage.Text = "Your video has been downloaded.";
        }
        private List<Uri> GetVideoDownloadUrls(string pageSource)
        {
            string pattern = "url=";
            string queryStringEnd = "&quality";

            List<Uri> finalURLs = new List<Uri>();
            List<string> urlList = Regex.Split(pageSource, pattern).ToList<string>();

            foreach (string url in urlList)
            {                
                string sURL = HttpUtility.UrlDecode(url).Replace("\\u0026", "&");

                int index = sURL.IndexOf(queryStringEnd, StringComparison.Ordinal);
                if (index > 0)
                {
                    sURL = sURL.Substring(0, index).Replace("&sig=", "&signature=");
                    finalURLs.Add(new Uri(Uri.UnescapeDataString(sURL)));
                }
            }

            return finalURLs;            
        }
        private string GetVideoTitle(string pageSource)
        {
            int startIndex = pageSource.IndexOf("<title>");
            int endIndex = pageSource.IndexOf("</title>");

            if (startIndex > -1 && endIndex > -1)
            {
                string title = pageSource.Substring(startIndex + 7, endIndex - (startIndex + 7));
                return title;
            }

            return "Unknown";
        }
Step5: Have a look at your target folder, you will see the Downloaded Video file.

Note: You might need to increase AsyncTimeOut on page directive in order to download larger videos. At the time of downloading video, even if you get TimeOut error, still the download will continue to target folder.

That's It! Thoutgh it is prety simple, it also involves the complexity of finding actual downloadable video URL.

Hope this helps! If you have any clarification on this, please leave a comment below.
You can also download complete source code from Dotnet4Techies code lab.

Download YouTube Videos using ASP.NET Download YouTube Videos using ASP.NET Reviewed by Srinivasa Rao Dhulipalla on November 14, 2012 4:26 PM Rating: 5

8 comments:

  1. hi, its working.. but downloading only small size videos. lesser 20 seconds videos.

    ReplyDelete
  2. Yes I am also getting size 0 kb. please resolve problem

    ReplyDelete
  3. Thanks for sharing use interview questions on .Net technology. While preparing for my job interview, your article helped me a lot to sharpen my skills and do well in my interview. One of trainer from leading dot net training institutes in Chennai suggests me about your site.

    ReplyDelete
  4. Updating with the latest technology and implementing it is the only way to survive in our niche. Thanks for making me understand through this article. You have done a great job by sharing this content in here. Keep writing article like this.

    .net training in chennai | DOT NET Training Institute in Chennai | DOT NET Course in Chennai

    ReplyDelete
  5. Considering that YouTube doesn't give any kind of direct download catch, It is difficult to download video cuts off YouTube. how to download youtube videos in android,

    ReplyDelete
  6. Believe this free youtube downloader for windows to take away all the YouTube recordings download issues that you have experienced previously. Visit our site today and locate this stunning free downloader. Life will never be the same again!youtube downloader android

    ReplyDelete

Powered by Blogger.