c# - 如何从 youtube 获取我的 youtube 视频列表?

标签 c# .net winforms youtube youtube-api

我安装了 google api 3 和 OAuth2。
我尝试了谷歌开发示例:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

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



namespace Youtube_Manager
{
    public partial class Form1 : Form
    {
        string devKey = "mykey";
        string userName = "my gmail as login";
        string Password = "mypass";
        string feedUrl = "https://gdata.youtube.com/feeds/api/users/default/playlists?v=2";
        YouTubeRequestSettings settings;

        public Form1()
        {
            InitializeComponent();

            settings = new YouTubeRequestSettings("Youtube Uploader", devKey);
            YouTubeRequest request = new YouTubeRequest(settings);

            Feed<Video> videoFeed = request.Get<Video>(new Uri(feedUrl));
            printVideoFeed(videoFeed);


        }

        static string auth;
        static void printVideoFeed(Feed<Video> feed)
        {
            foreach (Video entry in feed.Entries)
            {
                auth = entry.Author;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

第一个问题是链接https://gdata.youtube.com/feeds/api/users/default/playlists?v=2需要登录和密码我想当我试图浏览到这个链接时我得到:

需要用户认证。
错误 401

第二个问题是我不确定我使用的是正确的 key 。
我的应用程序名称是 Youtube Uploader,所以我去了谷歌控制台:
https://console.developers.google.com

在左侧我点击了 apis 并启用了:youtube data api v3
并且还启用了 YouTube Analytics API

然后我单击凭据并为 OAuth 创建了 key ,因此我现在有了客户端 ID key 电子邮件地址 key 和证书指纹

然后在它下面我创建了公共(public) api 访问并且我有 Api key 。

然后我去这个网站开始:https://code.google.com/apis/youtube/dashboard/gwt/index.html#product

在那里我看到了我的开发人员 key ,我还没有在我的 csharp 代码中使用它。

现在我想做的第一件事就是获取我自己的视频列表,我使用我今天/当前的登录名和密码在这种情况下以 Daniel Lipman 的名义上传到 youtube,当我登录时,我使用的是我的 gmail chocolade13091972 @gmail.com
我有一些几年前添加的视频。

所以问题是链接需要登录名和密码。并且不确定如何在我的代码中使用我的开发人员 key 用户名和密码。

我忘了提到,直到现在我才找到与我的开发人员 key 的链接,直到现在我试图将我的客户端 ID key 用作 devKey,我想我错了。现在我找到了我的开发者 key 长 key 。

编辑

我现在尝试了这个:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Threading;

using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;

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

namespace Youtube_Manager
{
    public partial class Form1 : Form
    {
        List<string> results = new List<string>();
        string devKey = "dev key";
        string apiKey = "api key";
        string userName = "my gmail address";
        string Password = "pass";

        public Form1()
        {
            InitializeComponent();

            Run();


        }

        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 for read-only access to the authenticated 
                    // user's account, but not other types of account access.
                    new[] { YouTubeService.Scope.YoutubeReadonly },
                    "user",
                    CancellationToken.None,
                    new FileDataStore(this.GetType().ToString())
                );
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = this.GetType().ToString()
            });

            var channelsListRequest = youtubeService.Channels.List("contentDetails");
            channelsListRequest.Mine = true;

            // Retrieve the contentDetails part of the channel resource for the authenticated user's channel.
            var channelsListResponse = await channelsListRequest.ExecuteAsync();

            foreach (var channel in channelsListResponse.Items)
            {
                // From the API response, extract the playlist ID that identifies the list
                // of videos uploaded to the authenticated user's channel.
                var uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads;

                Console.WriteLine("Videos in list {0}", uploadsListId);

                var nextPageToken = "";
                while (nextPageToken != null)
                {
                    var playlistItemsListRequest = youtubeService.PlaylistItems.List("snippet");
                    playlistItemsListRequest.PlaylistId = uploadsListId;
                    playlistItemsListRequest.MaxResults = 50;
                    playlistItemsListRequest.PageToken = nextPageToken;

                    // Retrieve the list of videos uploaded to the authenticated user's channel.
                    var playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync();

                    foreach (var playlistItem in playlistItemsListResponse.Items)
                    {
                        // Print information about each video.
                        //Console.WriteLine("{0} ({1})", playlistItem.Snippet.Title, playlistItem.Snippet.ResourceId.VideoId);
                        results.Add(playlistItem.Snippet.Title);
                    }

                    nextPageToken = playlistItemsListResponse.NextPageToken;
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

但它不会做任何不抛出异常或错误的事情。
我在行上使用了一个断点:
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))

在这条线之后什么都没有发生,它显示了form1,就是这样。

现在在构造函数中我改变并做了:
this.Run().Wait();

现在我在这条线上遇到了异常:
this.Run().Wait();

System.AggregateException was unhandled
  HResult=-2146233088
  Message=One or more errors occurred.
  Source=mscorlib
  StackTrace:
       at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
       at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
       at System.Threading.Tasks.Task.Wait()
       at Youtube_Manager.Form1..ctor() in d:\C-Sharp\Youtube-Manager\Youtube-Manager\Youtube-Manager\Form1.cs:line 43
       at Youtube_Manager.Program.Main() in d:\C-Sharp\Youtube-Manager\Youtube-Manager\Youtube-Manager\Program.cs:line 19
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.IO.FileNotFoundException
       HResult=-2147024894
       Message=Could not find file 'D:\C-Sharp\Youtube-Manager\Youtube-Manager\Youtube-Manager\bin\Debug\client_secrets.json'.
       Source=mscorlib
       FileName=D:\C-Sharp\Youtube-Manager\Youtube-Manager\Youtube-Manager\bin\Debug\client_secrets.json
       StackTrace:
            at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
            at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
            at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
            at Youtube_Manager.Form1.<Run>d__1.MoveNext() in d:\C-Sharp\Youtube-Manager\Youtube-Manager\Youtube-Manager\Form1.cs:line 51
       InnerException:

我在哪里可以找到这个文件:client_secrets.json 这是问题所在吗?

最佳答案

您正在尝试调用已不存在的 v2 URL(以 https://gdata 开头的 URL)。

此外,您获得开发者 key 的位置也已弃用;您不会使用“开发人员 key ”,而是使用从 console.developers.google.com 获得的 API key ——但不是客户端 ID。您需要创建一个“供公众访问的 API key ”。

完成所有这些后,请查看以下有效示例:https://developers.google.com/youtube/v3/code_samples/dotnet#retrieve_my_uploads

关于c# - 如何从 youtube 获取我的 youtube 视频列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30849252/

相关文章:

c# - MSChart:折线图 UI 看起来不正确

c# - Visual Studios 表单应用程序中的按钮

c# - C# 中删除文件中的特定字符串

c# - XNA CatmullRom 曲线

c# - 无法将类型 '.List<AnonymousType#1>' 隐式转换为 '.List<WebApplication2.Customer>'

.net - 引用Microsoft.SqlServer.Smo.dll

c# - 使用线程时检查条件失败

c# - Stream 意外结束,内容可能已被另一个组件读取。 Microsoft.AspNetCore.WebUtilities.MultipartReaderStream

c# - 获取两个工作日之间的天数差异

.net - 带有大字体的 Windows 对话框