C# YouTube : Google API

March 12, 2011 by C#   Integration   Google API     This post is marked as obsolete.

This week we had the opportunity to do some integration with YouTube for one of our clients - upload, edit, remove and displaying videos all in the "comfort" of their own website.

Initially we thought that we will probably need to do this using raw calls etc to YouTube (which we'd probably wrap into some sexy reusable classes), but luckily Google did all the work for us already via their data API - in a few lines of code one can for example upload a video to YouTube (like you will see in the following post).

Before you continue, you need to download the Google Data API (if you didn't already) and register for a YouTube developer key, you'll also need a username and password to access YouTube.

Lets jump into some code...

You'll need to add the following Google API references to your solution.



The following namespaces (located within the added references) are required:

using Google.YouTube;
using Google.GData.YouTube;
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Extensions.MediaRss;

Next you need to create an instance of the YouTubeRequestSettings class to which we pass all the settings required to connect to YouTube:

YouTubeRequestSettings settings = new YouTubeRequestSettings("applicationName", "developerKey", "userName", "passWord");

Upload a video to YouTube

YouTubeRequest request = new YouTubeRequest(settings);
Video newVideo = new Video();
newVideo.Title = "Test";
newVideo.Tags.Add(new MediaCategory("Animals", YouTubeNameTable.CategorySchema));
newVideo.Description = "Testing Testing Testing";
newVideo.YouTubeEntry.Private = false;
newVideo.YouTubeEntry.MediaSource = new MediaFileSource("C:\\test.wmv", "video/x-ms-wmv");
request.Upload(newVideo);

In the preceding snippet we pass our settings instance to a YouTubeRequest to which we pass a video using its Upload method.

Notice the Tags collection to which we add a MediaCategory - we're required to add our video to at least one category, a list of available categories can be found here.

When uploading large files to YouTube it might be prudent to set the YouTubeRequest's timeout, like see in the following piece of code.

((GDataRequestFactory)request.Service.RequestFactory).Timeout = 9999999;

List your uploaded videos

public IEnumerable<Video> ListMyVideos()
{
    YouTubeRequest request = new YouTubeRequest(settings);
    YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultUploads);
    Feed<Video> feed = request.Get<Video>(query);
    return feed != null ? feed.Entries : null;
}

In the snippet above we essentially create a simple query that returns all the videos the current logged in user (via YouTubeRequestSettings) uploaded to YouTube.

Get a video

public Video GetMyVideo(string uploader, string videoID)
{
    YouTubeRequest request = new YouTubeRequest(settings);
    Uri uri = new Uri(String.Format("http://gdata.YouTube.com/feeds/api/users/{0}/uploads/{1}", uploader, videoID));
    return request.Retrieve<Video>(uri);
}

In the preceding snippet we pass our YouTube username (minus its domain) and the ID of the video we wish to retrieve (you can get a list of videoID's in the snippet ahead of this one).

The video object returned by the Retrieve method (on the request), contains all kinds of useful information about the retrieved video e.g. length of the video, links to generated thumbnails etc.

Remove a video

public void Remove(Video video)
{
    YouTubeRequest request = new YouTubeRequest(settings);
    request.Delete(video);
}

To remove your video from YouTube is quite simple, simply pass the video retrieved from the GetVideo method (like seen in this post) to the Remove method seen above.

Update a video

public void Update(Video video, string title, string description)
{         
    YouTubeRequest request = new YouTubeRequest(settings);
    video.Title = title;
    video.Description = description;
    request.Update(video);
}

Similar to the Remove method, we simply pass our retrieved video to the YouTubeRequest object.

Display a video

Displaying a video is probably the easiest part in the whole process - in the past we used object/embed tags, but I noticed that YouTube migrated to iframes like seen in the following snippet.

<iframe title="YouTube video player" width="640" height="390" src="http://www.youtube.com/embed/somevideoID" frameborder="0" allowfullscreen></iframe>

Note: You can disable "related videos", by passing rel=0 to the url in the iframe eg. http://www.youtube.com/embed/somevideoID?rel=0 or even default it to HD by passing hd=1 to the url eg. http://www.youtube.com/embed/somevideoID?hd=1.

Above that, there is tons of customizations & settings we can set within YouTube itself for our uploaded videos - disabling comments, visibility (private / public / unlisted) etc.

Have fun...

Additional Reading
Developer's YouTube Guide for .NET


Leave a Comment


urgent help needed on my graduation project June 4, 2012 by Serhat

what exactly is the application name?

Show Error 401 April 12, 2012 by soni

hi All i try to upload a video file on you tube and file size around 4.2 MB but it give some exception. Please help me some one it's urgent Thanks in Adv. Here is My Code YouTubeRequestSettings settings = new YouTubeRequestSettings("Uploader", "AI39si66nbHM_NPGYG0Zk1ulP5IRoqpbSnobh81T7lHa8iZ3ckcL6IDsBUaMcnw63_pWV2gADw_-fy9XTKl1iUAPF_IbIkZLDw", "myusername", "mypassword"); YouTubeRequest request = new YouTubeRequest(settings); Video newVideo = new Video(); newVideo.Title = "Test"; newVideo.Tags.Add(new MediaCategory("Animals", YouTubeNameTable.CategorySchema)); newVideo.Description = "Testing Testing Testing"; newVideo.YouTubeEntry.Private = false; newVideo.YouTubeEntry.MediaSource = new MediaFileSource("D:\\video.wmv", "video/x-ms-wmv"); ((GDataRequestFactory)request.Service.RequestFactory).Timeout = 9999999; request.Upload(newVideo); MessageBox.Show("Done"); ============================================================= Give Below The Error Msg --------------------------- --------------------------- Google.GData.Client.GDataRequestException: Execution of request failed: http://uploads.gdata.youtube.com/feeds/api/users/default/uploads ---> System.Net.WebException: The remote server returned an error: (401) Unauthorized. at System.Net.HttpWebRequest.GetResponse() at Google.GData.Client.GDataRequest.Execute() --- End of inner exception stack trace --- at Google.GData.Client.GDataRequest.Execute() at Google.GData.Client.GDataGAuthRequest.Execute(Int32 retryCounter) at Google.GData.Client.GDataGAuthRequest.Execute() at Google.GData.Client.MediaService.EntrySend(Uri feedUri, AtomBase baseEntry, GDataRequestType type, AsyncSendData data) at Google.GData.Client.Service.Insert(Uri feedUri, AtomEntry newEntry, AsyncSendData data) at Google.GData.Client.Service.Insert[TEntry](Uri feedUri, TEntry entry) at Google.GData.YouTube.YouTubeService.Upload(String userName, YouTubeEntry entry) at Google.YouTube.YouTubeRequest.Upload(String userName, Video v) at Google.YouTube.YouTubeRequest.Upload(Video v) at uploader.Form1.button1_Click(Object sender, EventArgs e) in D:\uploader\uploader\Form1.cs:line 44 --------------------------- OK ---------------------------

image url February 18, 2012 by wahab

can any one tell me how to add imagre url in youtube url in you videos. video should show thaat image

February 11, 2012 by Christoff Truter

Hi Aftab I will look into captions/subtitles for you.

February 11, 2012 by Christoff Truter

Hi Carlos Can you give me more details on the exception you're receiving?

parameters to YouTubeRequestSettings constructor February 10, 2012 by Carlos

YouTubeRequestSettings settings = new YouTubeRequestSettings("applicationName", "developerKey", "userName", "passWord"); Hi I would like to know where I can get this applicationName parameter i have created an app into the youtube dashboard and get the developer key but i received an error using this snippet YouTubeRequestSettings settings = new YouTubeRequestSettings("TesterASP", "AI39si4efL2wqv3ZheWh5DJh7hOEJ7l1B2C7tVuxlc1CYh6hrduDijnHpjFbZ_8gjrLYiNJ0w_0SweEs3RajG5v4fMYiFQry4g", "myaccount", "mypass*"); YouTubeRequest request = new YouTubeRequest(settings); Video newVideo = new Video(); newVideo.Title = "Test"; newVideo.Tags.Add(new MediaCategory("Animals", YouTubeNameTable.CategorySchema)); newVideo.Description = "Testing Testing Testing"; newVideo.YouTubeEntry.Private = false; newVideo.YouTubeEntry.MediaSource = new MediaFileSource("C:\\TEST.3GP", "video/x-ms-wmv"); request.Upload(newVideo); Can u help me ASAP. thx

captions and subtitles February 9, 2012 by aftab afridi

hi i need to upload captions and subtitles to my youtube video through API but there is no method for C# can you help me ho to do it in C#, Thanks in advance.

October 16, 2011 by Anonymous

Hi ! YouTube API suggest Feed<Video> feed = request.GetFavoriteVideo(username) for fetching a user's favorite videos, but I cannot find it in .NET class library. All I can find is request.GetFavoriteFeed("xxxx"). But this does not seem to work. Also, if I use Google login (Client Login method), is there any way I can fetch the YouTube username of the logged in user? Thanks in advance Niladri

Got the URL September 7, 2011 by Saurabh

Thank you Christoff I got the URL for the video. Here is the code used. Video uploadedVideo = request.Upload(newVideo); VideoURL string = UploadedVideo.WatchPage;

Re: Get Url September 6, 2011 by Christoff Truter

Hi Saurabh The upload method on the request object returns a video object which contains all the information you'll need. eg. Video uploadedVideo = request.Upload(newVideo);