Saturday 3 August 2019

Download YouTube Videos using ASP.NET

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).
?
1
2
3
4
5
6
7
8
<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.
?
1
2
3
4
protected void btnDownload_Click(object sender, EventArgs e)
{
    DownloadYouTubeVideo();
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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;
    }
}
?
1
2
3
4
private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
    lblMessage.Text = "Your video has been downloaded.";
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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;           
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
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.

No comments:

Post a Comment