C# Google 驱动器 API 我个人驱动器中的文件列表

C# Google Drive API list of files from my personal drive

我正在尝试连接到我自己的个人 Google 云端硬盘帐户并收集文件名列表。

我做了什么:

  1. 安装了所有需要的 NuGet 包
  2. 已将 Google 驱动器添加到 Google 开发人员控制台中的 API 管理器
  3. 设置 Service Account 并下载 P12 密钥进行身份验证
  4. 写了下面的代码来调用API:

    string EMAIL = "myprojectname@appspot.gserviceaccount.com";
    string[] SCOPES = { DriveService.Scope.Drive };
    StringBuilder sb = new StringBuilder();
    
    X509Certificate2 certificate = new X509Certificate2(@"c:\DriveProject.p12",
                                   "notasecret", X509KeyStorageFlags.Exportable);
    ServiceAccountCredential credential = new ServiceAccountCredential(
       new ServiceAccountCredential.Initializer(EMAIL) { 
         Scopes = SCOPES 
       }.FromCertificate(certificate)
    );
    
    DriveService service = new DriveService(new BaseClientService.Initializer() { 
       HttpClientInitializer = credential
    });
    
    FilesResource.ListRequest listRequest = service.Files.List();
    IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute().Files;
    if (files != null && files.Count > 0)
        foreach (var file in files)
            sb.AppendLine(file.Name);
    

这段代码似乎工作正常。问题是我只得到一个文件 returned,它被命名为 "Getting started.pdf",我不知道它到底是从哪里来的。我认为问题很明显是我的个人 Google Drive 帐户没有连接到此代码。如何从我的个人 Google 云端硬盘帐户中调用 return 文件?

我能找到的唯一帮助是试图让您在您的界面中访问任何 最终用户Google 云端硬盘帐户。我的情况与此不同。我只想连接到 我的 Google 后台驱动帐户。

您正在连接的服务帐户连接到您的个人google驱动器帐户。将服务帐户视为自己的用户,它有自己的 Google 驱动器帐户。 运行ning files.list 显然现在上面没有任何文件。

解决方案一:

将一些文件上传到服务帐户Google驱动器帐户

方案二:

获取服务帐户电子邮件地址,并像其他任何用户一样与服务帐户共享 google 驱动器帐户上的文件夹。我不确定是否可以共享完整的驱动器帐户。如果您设法共享根文件夹,请告诉我:)

评论更新:打开google驱动网站。右键单击文件夹单击与他人共享。添加服务帐户电子邮件地址。繁荣它有访问权限。

方案三:

切换到 Oauth2 验证代码一次,在那里你可以随时获得刷新令牌 运行 那里的应用程序之后只需使用该刷新令牌即可访问你的个人驱动器帐户。

评论更新:您必须手动验证一次。之后,客户端库将为您加载刷新令牌。它存储在机器上。

Oauth2 Drive v3 示例代码:

/// <summary>
/// This method requests Authentcation from a user using Oauth2.  
/// Credentials are stored in System.Environment.SpecialFolder.Personal
/// Documentation https://developers.google.com/accounts/docs/OAuth2
/// </summary>
/// <param name="clientSecretJson">Path to the client secret json file from Google Developers console.</param>
/// <param name="userName">Identifying string for the user who is being authentcated.</param>
/// <returns>DriveService used to make requests against the Drive API</returns>
public static DriveService AuthenticateOauth(string clientSecretJson, string userName)
{
    try
    {
        if (string.IsNullOrEmpty(userName))
            throw new Exception("userName is required.");
        if (!File.Exists(clientSecretJson))
            throw new Exception("clientSecretJson file does not exist.");

        // These are the scopes of permissions you need. It is best to request only what you need and not all of them
        string[] scopes = new string[] { DriveService.Scope.Drive };                   // View and manage the files in your Google Drive         
        UserCredential credential;
        using (var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read))
        {
            string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            credPath = Path.Combine(credPath, ".credentials/apiName");

            // Requesting Authentication or loading previously stored authentication for userName
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
                                                                     scopes,
                                                                     userName,
                                                                     CancellationToken.None,
                                                                     new FileDataStore(credPath, true)).Result;
        }

        // Create Drive API service.
        return new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "Drive Authentication Sample",
        });
    }
    catch (Exception ex)
    {
        Console.WriteLine("Create Oauth2 DriveService failed" + ex.Message);
        throw new Exception("CreateOauth2DriveFailed", ex);
    }
}