.NET Code Samples
Stay organized with collections
Save and categorize content based on your preferences.
AI-generated Key Takeaways
-
These code samples, available in the
dotnet
folder of the YouTube APIs code sample repository on GitHub, utilize the Google APIs Client Library for .NET to interact with the YouTube Data API. -
One code sample demonstrates how to create a private playlist using the
playlists.insert
method, allowing the authenticated channel to own it and also allowing the adding of a video to that same playlist. -
Another code sample uses the
playlistItems.list
method and thechannels.list
method to retrieve a list of videos uploaded to the authenticated user's channel. -
A separate code sample provides functionality to perform keyword-based searches through the
search.list
method, categorizing results into videos, channels, and playlists. -
The last code sample covers uploading a video to the channel associated with the request, using the
videos.insert
method to successfully complete the upload.
The following code samples, which use the Google APIs Client Library for .NET, are available for the YouTube Data API. You can download these code samples from the dotnet
folder of the YouTube APIs code sample repository on GitHub.
Create a playlist
The following code sample calls the API's playlists.insert
method to create a private playlist
owned by the channel authorizing the request.
usingSystem; usingSystem.IO; usingSystem.Reflection; usingSystem.Threading; usingSystem.Threading.Tasks; usingGoogle.Apis.Auth.OAuth2; usingGoogle.Apis.Services; usingGoogle.Apis.Upload; usingGoogle.Apis.Util.Store; usingGoogle.Apis.YouTube.v3; usingGoogle.Apis.YouTube.v3.Data; namespaceGoogle.Apis.YouTube.Samples { ///<summary> ///YouTubeDataAPIv3sample:createaplaylist. ///ReliesontheGoogleAPIsClientLibraryfor.NET,v1.7.0orhigher. ///Seehttps://developers.google.com/api-client-library/dotnet/get_started ///</summary> internalclassPlaylistUpdates { [STAThread] staticvoidMain(string[]args) { Console.WriteLine("YouTube Data API: Playlist Updates"); Console.WriteLine("=================================="); try { newPlaylistUpdates().Run().Wait(); } catch(AggregateExceptionex) { foreach(vareinex.InnerExceptions) { Console.WriteLine("Error: "+e.Message); } } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } privateasyncTaskRun() { UserCredentialcredential; using(varstream=newFileStream("client_secrets.json",FileMode.Open,FileAccess.Read)) { credential=awaitGoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, //ThisOAuth2.0accessscopeallowsforfullread/writeaccesstothe //authenticateduser's account. new[]{YouTubeService.Scope.Youtube}, "user", CancellationToken.None, newFileDataStore(this.GetType().ToString()) ); } varyoutubeService=newYouTubeService(newBaseClientService.Initializer() { HttpClientInitializer=credential, ApplicationName=this.GetType().ToString() }); //Createanew,privateplaylistintheauthorizeduser's channel. varnewPlaylist=newPlaylist(); newPlaylist.Snippet=newPlaylistSnippet(); newPlaylist.Snippet.Title="Test Playlist"; newPlaylist.Snippet.Description="A playlist created with the YouTube API v3"; newPlaylist.Status=newPlaylistStatus(); newPlaylist.Status.PrivacyStatus="public"; newPlaylist=awaityoutubeService.Playlists.Insert(newPlaylist,"snippet,status").ExecuteAsync(); //Addavideotothenewlycreatedplaylist. varnewPlaylistItem=newPlaylistItem(); newPlaylistItem.Snippet=newPlaylistItemSnippet(); newPlaylistItem.Snippet.PlaylistId=newPlaylist.Id; newPlaylistItem.Snippet.ResourceId=newResourceId(); newPlaylistItem.Snippet.ResourceId.Kind="youtube#video"; newPlaylistItem.Snippet.ResourceId.VideoId="GNRMeaz6QRI"; newPlaylistItem=awaityoutubeService.PlaylistItems.Insert(newPlaylistItem,"snippet").ExecuteAsync(); Console.WriteLine("Playlist item id {0} was added to playlist id {1}.",newPlaylistItem.Id,newPlaylist.Id); } } }
Retrieve my uploads
The following code sample calls the API's playlistItems.list
method to retrieve a list of videos
uploaded to the channel associated with the request. The code also calls the channels.list
method with the
mine
parameter set to true
to retrieve the playlist ID that identifies the channel's uploaded
videos.
usingSystem; usingSystem.IO; usingSystem.Reflection; usingSystem.Threading; usingSystem.Threading.Tasks; usingGoogle.Apis.Auth.OAuth2; usingGoogle.Apis.Services; usingGoogle.Apis.Upload; usingGoogle.Apis.Util.Store; usingGoogle.Apis.YouTube.v3; usingGoogle.Apis.YouTube.v3.Data; namespaceGoogle.Apis.YouTube.Samples { ///<summary> ///YouTubeDataAPIv3sample:retrievemyuploads. ///ReliesontheGoogleAPIsClientLibraryfor.NET,v1.7.0orhigher. ///Seehttps://developers.google.com/api-client-library/dotnet/get_started ///</summary> internalclassMyUploads { [STAThread] staticvoidMain(string[]args) { Console.WriteLine("YouTube Data API: My Uploads"); Console.WriteLine("============================"); try { newMyUploads().Run().Wait(); } catch(AggregateExceptionex) { foreach(vareinex.InnerExceptions) { Console.WriteLine("Error: "+e.Message); } } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } privateasyncTaskRun() { UserCredentialcredential; using(varstream=newFileStream("client_secrets.json",FileMode.Open,FileAccess.Read)) { credential=awaitGoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, //ThisOAuth2.0accessscopeallowsforread-onlyaccesstotheauthenticated //user's account, but not other types of account access. new[]{YouTubeService.Scope.YoutubeReadonly}, "user", CancellationToken.None, newFileDataStore(this.GetType().ToString()) ); } varyoutubeService=newYouTubeService(newBaseClientService.Initializer() { HttpClientInitializer=credential, ApplicationName=this.GetType().ToString() }); varchannelsListRequest=youtubeService.Channels.List("contentDetails"); channelsListRequest.Mine=true; //RetrievethecontentDetailspartofthechannelresourcefortheauthenticateduser's channel. varchannelsListResponse=awaitchannelsListRequest.ExecuteAsync(); foreach(varchannelinchannelsListResponse.Items) { //FromtheAPIresponse,extracttheplaylistIDthatidentifiesthelist //ofvideosuploadedtotheauthenticateduser's channel. varuploadsListId=channel.ContentDetails.RelatedPlaylists.Uploads; Console.WriteLine("Videos in list {0}",uploadsListId); varnextPageToken=""; while(nextPageToken!=null) { varplaylistItemsListRequest=youtubeService.PlaylistItems.List("snippet"); playlistItemsListRequest.PlaylistId=uploadsListId; playlistItemsListRequest.MaxResults=50; playlistItemsListRequest.PageToken=nextPageToken; //Retrievethelistofvideosuploadedtotheauthenticateduser's channel. varplaylistItemsListResponse=awaitplaylistItemsListRequest.ExecuteAsync(); foreach(varplaylistIteminplaylistItemsListResponse.Items) { //Printinformationabouteachvideo. Console.WriteLine("{0} ({1})",playlistItem.Snippet.Title,playlistItem.Snippet.ResourceId.VideoId); } nextPageToken=playlistItemsListResponse.NextPageToken; } } } } }
Search by keyword
The following code sample calls the API's search.list
method to retrieve search results
associated with a particular keyword.
usingSystem; usingSystem.Collections.Generic; usingSystem.IO; usingSystem.Reflection; usingSystem.Threading; usingSystem.Threading.Tasks; usingGoogle.Apis.Auth.OAuth2; usingGoogle.Apis.Services; usingGoogle.Apis.Upload; usingGoogle.Apis.Util.Store; usingGoogle.Apis.YouTube.v3; usingGoogle.Apis.YouTube.v3.Data; namespaceGoogle.Apis.YouTube.Samples { ///<summary> ///YouTubeDataAPIv3sample:searchbykeyword. ///ReliesontheGoogleAPIsClientLibraryfor.NET,v1.7.0orhigher. ///Seehttps://developers.google.com/api-client-library/dotnet/get_started /// ///SetApiKeytotheAPIkeyvaluefromtheAPIs & auth > Registeredappstabof ///https://cloud.google.com/console ///PleaseensurethatyouhaveenabledtheYouTubeDataAPIforyourproject. ///</summary> internalclassSearch { [STAThread] staticvoidMain(string[]args) { Console.WriteLine("YouTube Data API: Search"); Console.WriteLine("========================"); try { newSearch().Run().Wait(); } catch(AggregateExceptionex) { foreach(vareinex.InnerExceptions) { Console.WriteLine("Error: "+e.Message); } } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } privateasyncTaskRun() { varyoutubeService=newYouTubeService(newBaseClientService.Initializer() { ApiKey="REPLACE_ME", ApplicationName=this.GetType().ToString() }); varsearchListRequest=youtubeService.Search.List("snippet"); searchListRequest.Q="Google";//Replacewithyoursearchterm. searchListRequest.MaxResults=50; //Callthesearch.listmethodtoretrieveresultsmatchingthespecifiedqueryterm. varsearchListResponse=awaitsearchListRequest.ExecuteAsync(); List<string>videos=newList<string>(); List<string>channels=newList<string>(); List<string>playlists=newList<string>(); //Addeachresulttotheappropriatelist,andthendisplaythelistsof //matchingvideos,channels,andplaylists. foreach(varsearchResultinsearchListResponse.Items) { switch(searchResult.Id.Kind) { case"youtube#video": videos.Add(String.Format("{0} ({1})",searchResult.Snippet.Title,searchResult.Id.VideoId)); break; case"youtube#channel": channels.Add(String.Format("{0} ({1})",searchResult.Snippet.Title,searchResult.Id.ChannelId)); break; case"youtube#playlist": playlists.Add(String.Format("{0} ({1})",searchResult.Snippet.Title,searchResult.Id.PlaylistId)); break; } } Console.WriteLine(String.Format("Videos:\n{0}\n",string.Join("\n",videos))); Console.WriteLine(String.Format("Channels:\n{0}\n",string.Join("\n",channels))); Console.WriteLine(String.Format("Playlists:\n{0}\n",string.Join("\n",playlists))); } } }
Upload a video
The following code sample calls the API's videos.insert
method to upload a video to the channel
associated with the request.
usingSystem; usingSystem.IO; usingSystem.Reflection; usingSystem.Threading; usingSystem.Threading.Tasks; usingGoogle.Apis.Auth.OAuth2; usingGoogle.Apis.Services; usingGoogle.Apis.Upload; usingGoogle.Apis.Util.Store; usingGoogle.Apis.YouTube.v3; usingGoogle.Apis.YouTube.v3.Data; namespaceGoogle.Apis.YouTube.Samples { /// <summary> /// YouTube Data API v3 sample: upload a video. /// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher. /// See https://developers.google.com/api-client-library/dotnet/get_started /// </summary> internalclassUploadVideo { [STAThread] staticvoidMain(string[]args) { Console.WriteLine("YouTube Data API: Upload Video"); Console.WriteLine("=============================="); try { newUploadVideo().Run().Wait(); } catch(AggregateExceptionex) { foreach(vareinex.InnerExceptions) { Console.WriteLine("Error: "+e.Message); } } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } privateasyncTaskRun() { UserCredentialcredential; using(varstream=newFileStream("client_secrets.json",FileMode.Open,FileAccess.Read)) { credential=awaitGoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, // This OAuth 2.0 access scope allows an application to upload files to the // authenticated user's YouTube channel, but doesn't allow other types of access. new[]{YouTubeService.Scope.YoutubeUpload}, "user", CancellationToken.None ); } varyoutubeService=newYouTubeService(newBaseClientService.Initializer() { HttpClientInitializer=credential, ApplicationName=Assembly.GetExecutingAssembly().GetName().Name }); varvideo=newVideo(); video.Snippet=newVideoSnippet(); video.Snippet.Title="Default Video Title"; video.Snippet.Description="Default Video Description"; video.Snippet.Tags=newstring[]{"tag1","tag2"}; video.Snippet.CategoryId="22";// See https://developers.google.com/youtube/v3/docs/videoCategories/list video.Status=newVideoStatus(); video.Status.PrivacyStatus="unlisted";// or "private" or "public" varfilePath=@"REPLACE_ME.mp4";// Replace with path to actual movie file. using(varfileStream=newFileStream(filePath,FileMode.Open)) { varvideosInsertRequest=youtubeService.Videos.Insert(video,"snippet,status",fileStream,"video/*"); videosInsertRequest.ProgressChanged+=videosInsertRequest_ProgressChanged; videosInsertRequest.ResponseReceived+=videosInsertRequest_ResponseReceived; awaitvideosInsertRequest.UploadAsync(); } } voidvideosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgressprogress) { switch(progress.Status) { caseUploadStatus.Uploading: Console.WriteLine("{0} bytes sent.",progress.BytesSent); break; caseUploadStatus.Failed: Console.WriteLine("An error prevented the upload from completing.\n{0}",progress.Exception); break; } } voidvideosInsertRequest_ResponseReceived(Videovideo) { Console.WriteLine("Video id '{0}' was successfully uploaded.",video.Id); } } }