Upload a video to Youtube from .NET

Last week I was researching on how to upload videos to my Youtube account from NET. Basically all I need is a new project in Google Developers and the following code:

using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;

namespace UploadVideoYoutube
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //1. Nuget packages:
            //Install-Package Google.Apis -Version 1.8.1
            //Install-Package Google.Apis.YouTube.v3
            //Uninstall-Package Microsoft.Bcl.Async -Force
            //(Removing 'Microsoft.Bcl.Async 1.0.16' from UploadVideoYoutube)
            //Install-Package Microsoft.Bcl.Async -Version 1.0.166-beta -Pre

            try
            {
                //2. Get credentials and upload the file
                Upload().Wait();

            }
            catch (AggregateException ex)
            {
                foreach (var exception in ex.InnerExceptions)
                {
                    Console.WriteLine(exception.Message);
                }
            }

            Console.ReadLine();
        }

        private static async Task Upload()
        {
            //2.1 Get credentials
            UserCredential credentials;

            //2.1.1 Use https://console.developers.google.com/ to get the json file (Credential section)
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credentials = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { YouTubeService.Scope.YoutubeUpload },
                    "user",
                    CancellationToken.None);
            }

            //2.2 Create a YoutubeService instance using our credentials
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credentials,
                ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
            });

            //2.3 Create a video object
            var video = new Video()
            {
                Id = "myIdVeo",

                Status = new VideoStatus
                {
                    PrivacyStatus = "private"
                },

                Snippet = new VideoSnippet
                {
                    Title = "Testing Api from .NET",
                    Description = "Testing description",
                    Tags = new string[] { "myTag1", "myTag2" }
                }
            };

            var filePath = @"[FILE_PATH]";

            //2.4 Read and insert the video in youtubeService
            using (var fileStream = new FileStream(filePath, FileMode.Open))
            {
                var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                videosInsertRequest.ProgressChanged += ProgressChanged;
                videosInsertRequest.ResponseReceived += ResponseReceived;

                //2.4.1 Wait for the upload process
                await videosInsertRequest.UploadAsync();
            }
        }

        static void ProgressChanged(IUploadProgress progress)
        {
            switch (progress.Status)
            {
                case UploadStatus.Starting:
                    Console.WriteLine("Start uploading");
                    break;
                case UploadStatus.Uploading:
                    Console.WriteLine("{0} bytes sent.", progress.BytesSent);
                    break;
                case UploadStatus.Completed:
                    Console.WriteLine("Upload completed!");
                    break;
                case UploadStatus.Failed:
                    Console.WriteLine("An error prevented the upload from completing.n{0}", progress.Exception);
                    break;
            }
        }

        static void ResponseReceived(Video video)
        {
            Console.WriteLine("Video '{0}' was successfully uploaded.", video.Snippet.Title);
        }
    }
}

The first thing we need are Google.Apis and Google.Apis.YouTube.v3 libraries. At the time this post was written, there were some incompatibilities with the latest versions and associated dependencies, but it is possible to run the example with versions and packages listed in the comments. Because the process is called asynchronously, I’ve created a method called Upload where we do all the steps:

  1. Get the Youtube credentials: Once you’ve created the project in Google Developers will be able to use the Google APIs available for developers. You need to check that the Api YouTube Data API v3 is enabled:
     Google Developers Apis
    Also, we must create a new Client ID using OAuth to retrieve the JSON file with the necessary credentials for the connection:
     Create new Client ID
    The first time you run the example, a browser window will open to ask for access to the Google account linked to Youtube.

    To avoid errors it’s important to fill the Consent screen section of the project, at least the project name and the email associated.
  2. Create an instance of YoutubeService with the credentials obtained.
  3. Create a Video object and add some of the available properties, such as the type of access (private or public), title, description, tags, etc..
  4. Get the local video that we want to upload and insert it in the list of YoutubeService called Videos. We have also associated two handlers to events ProgressChange and ResponseReceived to be aware of the progress of the operation.
  5. Upload the file through UploadSync and wait for confirmation through the console.

To check the result from Youtube, just go to the following URL: https://www.youtube.com/user/[USER_NAME]/videos

Result upload video Youtube

Hope this helps.

Happy uploading!