我正在尝试连接到我自己的个人 Google 云端硬盘帐户并收集文件名列表。
我做了什么:
- 安装了所需的所有 NuGet 包
- 将 Google 云端硬盘添加到 Google Developers Console 中的 API 管理器
- 设置Service Account并下载了用于身份验证的 P12 key
编写以下代码来调用API:
string EMAIL = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="14796d64667b7e7177607a7579715475646467647b603a73677166627d77717577777b617a603a777b79" rel="noreferrer noopener nofollow">[email protected]</a>"; 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);
这段代码看起来工作正常。问题是我只得到一个返回的文件,它的名字是“Getting started.pdf”,我不知道它到底来自哪里。我认为问题显然是我的个人 Google Drive 帐户没有连接到此代码。如何接到此电话以从我的个人 Google 云端硬盘帐户返回文件?
我能找到的唯一帮助是尝试让您在界面中访问任何最终用户 Google 云端硬盘帐户。我的情况与此不同。我只想在后台连接到我的 Google 云端硬盘帐户。
最佳答案
您正在连接的服务帐户未连接到您的个人 Google 云端硬盘帐户。将服务帐户视为自己的用户,它有自己的 Google 云端硬盘帐户。通过运行 files.list 显然现在上面没有任何文件。
解决方案 1:
将一些文件上传到服务帐户 Google 云端硬盘帐户
解决方案 2:
获取服务帐户电子邮件地址,并与服务帐户共享您的 Google 云端硬盘帐户上的文件夹,就像与任何其他用户一样。我不确定是否可以共享完整的驱动器帐户。如果您设法共享根文件夹,请告诉我:)
评论更新:打开谷歌驱动器网站。右键单击该文件夹,然后单击与他人共享。添加服务帐户电子邮件地址。繁荣它可以访问。
解决方案 3:
切换到 Oauth2 验证代码一次,只要使用该刷新 token 即可访问您的个人驱动器帐户,您就可以在任何时候运行应用程序时获得刷新 token 。
评论更新:您必须手动验证一次。之后,客户端库将为您加载刷新 token 。它存储在机器上。
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);
}
}
关于.net - 我的个人硬盘中的 C# Google Drive API 文件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36024253/