C# YouTube : Google API

March 12, 2011 by Christoff Truter C#   Integration  

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


Multiple Upload July 15, 2014 by Rishad1

I need to upload multiple videos to you tube please help..

Thanks and Async November 16, 2012 by Anonymous

Hey there. Thank you for posting that friendly examples. They really helped me a lot. They worked fine but my project required an async operation for the upload and luckyly I have found an other helpful example posted here: https://groups.google.com/forum/?fromgroups=#!topic/youtube-api-gdata/IbAyA8cLNWo Maybe that helps also someone else so I want to share it here beside your nice tutorial. Maybe you want to add it anyway as an optional way with progress output. Instead of: request.Upload(newVideo); Use: request.Service.InsertAsync(new Uri("http://uploads.gdata.youtube.com/feeds/api/users/default/uploads"), newVideo.AtomEntry, newVideo); request.Service.AsyncOperationProgress += new AsyncOperationProgressEventHandler(Progress); And add: public void Progress(object sender, AsyncOperationProgressEventArgs e) { MyProgressVariable = e.ProgressPercentage; }

November 8, 2012 by Anonymous

Thank You for sharing. Was very helpful for me

post comment October 30, 2012 by Anonymous

how to post a comment on a youtube video through c#

for loop September 27, 2012 by Anonymous

string url = "http://gdata.youtube.com/feeds/videos?q="; AtomFeed myFeed = GetFeed(url, i, 50); DisplayFeed(myFeed); how would i get loop for generating 1000 number of items in the output can any one help me

list youtube videos September 25, 2012 by Abhinand

hey im nt geting exact code for searching list of youtube videos on search of a perticular keyword can u plz help me out

Get a Video September 24, 2012 by Ashok

Hi, i am using different userid but i cant get video belongs to that corresponding user intead of that i am gettting following error "Execution of request failed: https://gdata.youtube.com/feeds/api/users/ashok/uploads" i need to know why these kind of exception is coming.

Help me September 17, 2012 by Anonymous

Hi Christoff Truter!, I want to upload a video to youtube by way open file dialog and choose file from my computer, but not type path file video same as "C:\\test.wmv", please help me!. I am not fluent english, if it anything make you not glad, forgive me!.

August 3, 2012 by Christoff Truter

Hi Shaahin Something like this: Video uploadedVideo = request.Upload(newVideo); VideoURL string = UploadedVideo.WatchPage;

return URL August 3, 2012 by Shaahin

Really nice article. My question is how to get URL of uploaded video? Thanks in advance


Latest Posts

Enhance Customer Registration Process with Cutting-Edge Solutions from Card Scanning Solutions Inc.

November 4, 2013

JavaScript Threading - Part 2 (Worker)

December 18, 2012

JavaScript Threading - Part 1 (Timers)

December 18, 2012

MS SQL: Parameter Sniffing

May 21, 2012

Solving Cross Browser Issues - Part 3 (Mootools and HTML5)

February 23, 2012

Solving Cross Browser Issues - Part 2 (GWT and Dart)

February 7, 2012

Solving Cross Browser Issues - Part 1 (JQuery and GWT)

January 9, 2012

Be the best stalker you can be

December 13, 2011

AjaxControlToolkit (ASP.NET/C#) : CascadingDropDown Extender - Part 2

November 3, 2011

AjaxControlToolkit (ASP.NET/C#) : CascadingDropDown Extender - Part 1

October 7, 2011


Most Commented on Posts

Moving items between listboxes in ASP.net/PHP example

Move items between two listboxes in ASP.net(C#, VB.NET) and PHP
June 12, 2008

Simple WYSIWYG Editor

Creating a WYSIWYG textbox for your website is actually quite simple.
February 1, 2007

C# YouTube : Google API

Post on how to integrate with YouTube using the Google Data API
March 12, 2011

Populate a TreeView Control C#

Populate a TreeView control in a windows application.
August 27, 2009

Cross Browser Issues: Firefox Word Wrapping

Firefox word wrapping issues
June 9, 2008


ASP.NET   C#   C++   Comedy   Cross Browser   Design Patterns   IIS   Integration   JavaScript   Microsoft Office   Personal   PHP   SQL   Threading   Visual Basic   XML