Upload a video do not work with the YouTube API v3 - c#

[STAThread]
static void Main(string[] args)
{
Console.WriteLine("YouTube Data API: Upload Video");
Console.WriteLine("==============================");
try
{
new UploadVideo().Run().Wait();
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("Error: " + e.Message);
}
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
private async Task Run()
{
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.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
);
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
var video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = "Default Video Title";
video.Snippet.Description = "Default Video Description";
video.Snippet.Tags = new string[] { "tag1", "tag2" };
video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
var filePath = "video2.mp4"; // Replace with path to actual movie file.
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;
await videosInsertRequest.UploadAsync();
}
}
void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
{
switch (progress.Status)
{
case UploadStatus.Uploading:
Console.WriteLine("{0} bytes sent.", progress.BytesSent);
break;
case UploadStatus.Failed:
Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
break;
}
}
void videosInsertRequest_ResponseReceived(Video video)
{
Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
}
But i am getting progress.Status is Failed every time.I am unable to upload a video to youtube. My video file size is 2MB.and I am create clientid and secret key for webapplication in https://console.developers.google.com. Can any one help me to resolve this please.
Thanks in advance

You was created clientid and secret key for webapplication.
Must create key for installed. And download the JSON file.
Rename the JSON file name to "client_secrets.json".
And save to bin/Debug ot bin/Release as same *.exe as directory.

Related

youtube-v3-api "Failed to launch browser with "https://accounts.google.com/o/oauth2/v2/auth?

Hi I am working on an Web application that uploads a video to the users Youtube Channel. I used the code which is given in the google Youtube API guide.
static void Main(string[] args)
{
Console.WriteLine("YouTube Data API: Upload Video");
Console.WriteLine("==============================");
try
{
new UploadVideo().Run().Wait();
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("Error: " + e.Message);
}
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
private async Task Run()
{
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.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
);
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
var video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = "Default Video Title";
video.Snippet.Description = "Default Video Description";
video.Snippet.Tags = new string[] { "tag1", "tag2" };
video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
var filePath = #"REPLACE_ME.mp4"; // Replace with path to actual movie file.
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
await videosInsertRequest.UploadAsync();
}
}
This code works fine when I run it in visual studio locally and the video gets uploaded to my Youtube channel. But the problem which I face is when I host the application in the IIS at a server machine it throws a Access Denied exception to the folder
'C:\Windows\system32\config\systemprofile'
I gave the permission to the folder and now it threw an different exception
"Failed to launch browser with "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id=MY_CLIENT_ID&redirect_uri=http%3A%2F%2Flocalhost%3A62196%2Fauthorize%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.upload" for authorization. See inner exception for details."

Getting an 'UnauthorizedAccessException' when try to download a file from Google Drive using c# code

I am trying to download a file from Google Drive using the following code.
when it reach SaveStream() function it throwing an UnauthorizedAccessException.
As per some suggesstions I set the access permissions of that folder to Full control.But its not working for me now also I am getting the same Exception.
namespace BackEnd.Controllers
{
public class GoogleDriveController : Controller
{
// GET: GoogleDrive
static string[] Scopes = { DriveService.Scope.DriveReadonly };
static string ApplicationName = "Drive API .NET Quickstart";
public ActionResult Index()
{
UserCredential credential;
using (var stream = new FileStream(#"D:\client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
// Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
FilesResource.ListRequest listRequest = service.Files.List();
listRequest.MaxResults = 10;
IList<Google.Apis.Drive.v2.Data.File> files = listRequest.Execute().Items;
if (files != null && files.Count > 0)
{
foreach (var file in files)
{
DownloadFile(service, file, string.Format(#"D:\Photos"));
}
}
return View();
}
private static void DownloadFile(Google.Apis.Drive.v2.DriveService service, Google.Apis.Drive.v2.Data.File file, string saveTo)
{
var request = service.Files.Get(file.Id);
var stream = new System.IO.MemoryStream();
request.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) =>
{
switch (progress.Status)
{
case Google.Apis.Download.DownloadStatus.Downloading:
{
// (progress.BytesDownloaded);
break;
}
case Google.Apis.Download.DownloadStatus.Completed:
{
//"Download complete.";
SaveStream(stream, saveTo);
break;
}
case Google.Apis.Download.DownloadStatus.Failed:
{
//"Download failed.";
break;
}
}
};
request.Download(stream);
}
private static void SaveStream(System.IO.MemoryStream stream, string saveTo)
{
using (System.IO.FileStream file = new System.IO.FileStream(saveTo, System.IO.FileMode.Create, System.IO.FileAccess.Write))
{
stream.WriteTo(file);
}
}
}
}

YouTube Data API for Uploading Videos not working in mvc

i am trying to upload a video to YouTube by using YouTube data API, from my application but unfortunately the API which provided by YouTube developers
https://developers.google.com/youtube/v3/code_samples/dotnet#upload_a_video
is not working before three weeks i tested the code and it was working fine but now when i try to finally use it in my application its causing a problem all the code is working fine but when the video uploading process starts it's became loading and loading and the video doesn't uploaded i google it but not find any help. if some one can help me ? here is my code which i am using
private async Task Run()
{
UserCredential credential;
using (var stream = new FileStream("G:\\client_secret_783534382593-0cn4gm229raqq97kdu0ghsj9hqfsc5o1.apps.googleusercontent.com.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.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
);
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
var video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = "ttry";
video.Snippet.Description = " Video Description";
video.Snippet.Tags = new string[] { "tag1s", "tag2s" };
video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "public"; // or "private" or "publi
var filePath = "F:\\Dna.MP4"; // Replace with path to actual movie file.
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;
await videosInsertRequest.UploadAsync();
}
}
void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
{
switch (progress.Status)
{
case UploadStatus.Uploading:
Console.WriteLine("{0} bytes sent.", progress.BytesSent);
break;
case UploadStatus.Failed:
Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
break;
}
}
void videosInsertRequest_ResponseReceived(Video video)
{
Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
}
}
}
and i am simply calling it from this action
public ActionResult Contact()
{
Run().Wait();
return View();
}
i wonder that why it is not working ? when i debug it then all the things and parameters are fine even credentials are also fine but at the end the file is not uploading even i am selecting 1 MB file and i also included all the necessary NuGet packages kindly some one help me please ?
the problem is solve by simply adding some bit of code in Get Function
public async Task<ActionResult> Contact()
{
await Run();
return View();
}

How to upload video to youtube specific channelID in C#

I am able to successfully upload a video to my youtube account in C# using the following code:
private async Task Run(string videoFile, string dateStamp)
{
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.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.Youtubepartner},
"user",
CancellationToken.None
);
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
var video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = string.Format("{0} - La Jolla boat launch timelapse", dateStamp);
video.Snippet.Description = "Daily TimeLapse of the boat launch area.";
video.Snippet.Tags = new string[] { "LaJolla", "timelapse" };
video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
video.Snippet.ChannelId = "UC8LB7gACPEoNxdAK6LM-L6A";
video.Snippet.ChannelTitle = "TimeLapse La Jolla";
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "public"; // or "private" or "public"
var filePath = videoFile; // Replace with path to actual movie file.
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;
await videosInsertRequest.UploadAsync();
}
}
However, I have 3 channels in my youtube account and would like to upload to a specific channel. The code above will upload to my main account without issue, but not to the channel ID supplied. The channel name and ID are correct - but this is not working as I expected the video to appear as a new upload in the channel. I am not able to find additional information for this functionality. Any suggestions?
Code is from youtube API samples.
Thanks for looking.

It doesn't work to upload a video to youtube with Google API V3 with Web JSON in a ASP.NET Web Forms application

I have bellow follow code inspired from sample youtube google api upload video.
I generated Web JSON for my domain, when i run this code i write with Debug.Write in log file but i see in log wrote only "Inside Run" doesn't pass after AuthorizeAsync method and neither error received, do you have any idea why doesn't works ?
In console application with native JSON generated works ok.
My web application is ASP.NET Web Forms.
public async Task Run()
{
Debug.Write("Inside Run");
UserCredential credential = null;
try
{
using (var stream = new FileStream(ClientSecretJson, FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.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
);
}
}
catch (Exception ex)
{
Debug.Write(ex.Message);
//File.AppendAllText("exceptie.txt", ex.Message);
}
Debug.Write("After Authentification");
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
var video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = TitleVideo;
video.Snippet.Description = Description;
video.Snippet.Tags = new string[] { "tag1", "tag2" };
video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "public"; // or "private" or "public"
var filePath1 = FilePath; // Replace with path to actual movie file.
using (var fileStream = new FileStream(filePath1, FileMode.Open))
{
var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;
videosInsertRequest.Upload();
}
}
void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
{
switch (progress.Status)
{
case UploadStatus.Uploading:
Debug.WriteLine("{0} bytes sent.", progress.BytesSent);
lbl.Text += "<br> " + string.Format("{0} bytes sent.", progress.BytesSent);
break;
case UploadStatus.Failed:
Debug.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
lbl.Text += "<br> " + string.Format("An error prevented the upload from completing.\n{0}", progress.Exception);
break;
}
}
void videosInsertRequest_ResponseReceived(Video video)
{
Debug.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
lbl.Text += "<br> " + string.Format("Video id '{0}' was successfully uploaded.", video.Id);
}

Categories