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.";
}

No comments:
Post a Comment