Retrieve A Single YouTube Video in .NET
- Published on
- -2 min read
Back in 2009 I wrote a simple web application to output all videos uploaded from a user’s channel. Luckily, hardly anything has changed. Now you only need to register for a Developer Key and state an Application Name. You are no longer required to provide a Client ID.
This time round, I needed to output data onto my page from a single YouTube entry when a user pastes the URL of a YouTube video in one of my form fields.
using System;
using System.Linq;
using System.Text;
using Google.GData;
using Google.YouTube;
using Google.GData.Client;
namespace MyProject.Helpers.Common
{
public class YouTubeHelper
{
private static string YouTubeDeveloperKey = WebConfigurationManager.AppSettings["YouTubeDeveloperKey"].ToString();
private static string YouTubeAppName = WebConfigurationManager.AppSettings["YouTubeAppName"].ToString();
//Get YouTube video
public static Video YouTubeVideoEntry(string videoID)
{
YouTubeRequestSettings settings = new YouTubeRequestSettings(YouTubeAppName, YouTubeDeveloperKey);
YouTubeRequest request = new YouTubeRequest(settings);
//Link to the feed we wish to read from
string feedUrl = String.Format("http://gdata.youtube.com/feeds/api/videos/{0}", videoID);
Feed<Video> videoFeed = request.Get<Video>(new Uri(feedUrl));
return videoFeed.Entries.SingleOrDefault();
}
//Extract the YouTube ID from the web address.
public static string GetVideoID(string videoUrl)
{
Uri tempUri = new Uri(videoUrl);
string sQuery = tempUri.Query;
return System.Web.HttpUtility.ParseQueryString(sQuery).Get("v");
}
//Get required YouTube video information
public static YouTubeDetail GetVideoInformation(string url)
{
Video v = YouTubeVideoEntry(GetVideoID(url));
//Pass required YouTube information to custom class called YouTubeDetail
YouTubeDetail vDetail = new YouTubeDetail();
vDetail.ID = v.VideoId;
vDetail.Title = v.Title;
vDetail.Description = v.Description;
return vDetail;
}
}
}
Hopefully, my “YouTubeHelper” class is easy to follow. All you need to use is the “GetVideoInformation()” method by simply passing a page link to where your YouTube video resides. At the moment only full YouTube URL’s are accepted not the short URL (http://youtu.be/).
Before you go...
If you've found this post helpful, you can buy me a coffee. It's certainly not necessary but much appreciated!
Leave A Comment
If you have any questions or suggestions, feel free to leave a comment. Your comment will not only help others, but also myself.