C#Google Drive API我的个人驱动器中的文件列表 [英] C# Google Drive API list of files from my personal drive
问题描述
我尝试连接到自己的Google云端硬盘帐户并收集文件名称列表。
我所做的:
- 安装所有需要的NuGet软件包
- 将Google Drive添加到Google Developers Console中的API Manager
- 设置服务帐户并下载P12密钥用于身份验证
-
写下面的代码来调用API:
string EMAIL =myprojectname@appspot.gserviceaccount.com;
string [] SCOPES = {DriveService.ScopeDrive};
StringBuilder sb = new StringBuilder();
X509Certificate2 certificate = new X509Certificate2(@c:\\DriveProject.p12,
notasecret,X509KeyStorageFlags.Exportable);
ServiceAccountCredential凭证=新的ServiceAccountCredential(
新的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&& file.Count> 0)
foreach(文件中的var文件)
sb.AppendLine(file.Name);
这段代码似乎工作正常。问题是我只返回一个文件,它被命名为Getting started.pdf,我不知道它来自哪里。我认为问题很明显,我的个人Google云端硬盘帐户未连接到此代码。如何获得此通话以便从我的个人Google云端硬盘帐户中返回文件?
我能够找到的唯一帮助是试图让您访问您的界面中的任何最终用户Google云端硬盘帐户。我的情况与此不同。我只想在幕后连接到我的 Google云端硬盘帐户。 服务帐户不连接到您的个人Google云端硬盘帐户。将服务帐户视为自己的用户,它拥有自己的Google云端硬盘帐户。通过运行files.list显然现在没有任何文件。
解决方案1: 将一些文件上传到服务帐户Google云端硬盘帐户 解决方案2: 取得服务帐户的电子邮件地址并共享一个文件夹在您的谷歌驱动器帐户与服务帐户像你会任何其他用户。我不确定是否有可能共享一个完整的驱动器帐户。让我知道,如果你设法共享根文件夹:) 更新评论:打开谷歌驱动器的网站。右键点击文件夹点击与他人共享。添加服务帐户的电子邮件地址。它可以访问。 解决方案3: 更新评论:您必须手动验证一次。之后,客户端库将为您加载刷新令牌。它存储在机器上。 I am trying to connect to my own personal Google Drive account and gather a list of file names. What I have done: Wrote the following code to call the API: This code seems to be working fine. The problem is I only get a single file returned, it is named "Getting started.pdf" and I have no idea where the hell it is coming from. I think the problem is clearly that my personal Google Drive account is not wired up to this code. How do I get this call to return the files from my personal Google Drive account? The only help I was able to find was trying to get you to access any end users Google Drive account in your interface. My scenario is different than that. I only want to connect to my Google Drive account behind the scenes. You are connecting with a service account which does not connect to your personal google drive account. Think of a service account as its own user, it has its own Google drive account. Which by running files.list apparently right now doesn't have any files on it. Solution 1: Upload some files to the Service accounts Google drive account Solution 2: Take the service account email address and share a folder on your google drive account with the service account like you would any other user. I am not sure if its possible to share a full drive account or not. Let me know if you manage to share the root folder :) Update for comment: Open google drive the web site. right click the folder click share with others. Add the service account email address. Boom it has access. Solution 3: Switch to Oauth2 authenticate the code once where by you get a refresh token anytime you run the application there after just use that refresh token to gain access to your personal drive account. Update for comment: You will have to authenticate it manually once. After that the client library will load the refresh token for you. Its stored on the machine. Oauth2 Drive v3 sample code:
这篇关于C#Google Drive API我的个人驱动器中的文件列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
$ b Oauth2 Drive v3示例代码:
///< summary>
///此方法使用Oauth2从用户请求认证。
///凭证存储在System.Environment.SpecialFolder.Personal
///文档中https://developers.google.com/accounts/docs/OAuth2
///< /总结>
///< param name =clientSecretJson> Google Developers控制台中客户端密钥json文件的路径。< / param>
///< param name =userName>为正在验证的用户识别字符串。< / param>
///<返回>用于向Drive API发出请求的DriveService< /返回>
public static DriveService AuthenticateOauth(string clientSecretJson,string userName)
{
try
{
if(string.IsNullOrEmpty(userName))
throw new Exception (用户名是必需的。);
if(!File.Exists(clientSecretJson))
抛出新异常(clientSecretJson文件不存在。);
//这些是您需要的权限范围。最好只请求你所需要的而不是全部
string [] scopes = new string [] {DriveService.ScopeDrive}; //查看和管理您的Google云端硬盘中的文件
UserCredential凭据;
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);
//请求为userName
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,$ b $ scopes,
userName,
CancellationToken.None,
FileDataStore(credPath,true))。
}
//创建Drive API服务。
返回新的DriveService(新的BaseClientService.Initializer()
{
HttpClientInitializer =凭证,
ApplicationName =Drive Authentication Sample,
});
catch(Exception ex)
{
Console.WriteLine(Create Oauth2 DriveService failed+ ex.Message);
抛出新的异常(CreateOauth2DriveFailed,前);
}
}
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);
/// <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);
}
}