c# - 在 C# 中从谷歌驱动器文件中获取元数据
问题描述
我正在尝试获取有关所有 Google Drive 的元数据信息。这是我的代码:
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Green;
var clientId = "MyID";
var secret = "MySecret";
var service = GoogleDriveFileListDirectoryStructure.AuthenticateOauth(clientId, secret, "AppliUserAutor2");
var allFiles = GoogleDriveFileListDirectoryStructure.ListAll(service, new GoogleDriveFileListDirectoryStructure.FilesListOptionalParms { Q = "('root' in parents)", PageSize = 1000 });
GoogleDriveFileListDirectoryStructure.PrettyPrint(service, allFiles, "");
Console.ReadLine();
}
internal class GoogleDriveFileListDirectoryStructure
{
public static DriveService AuthenticateOauth(string clientId, string clientSecret, string userName)
{
try
{
if (string.IsNullOrEmpty(clientId))
throw new ArgumentNullException("clientId");
if (string.IsNullOrEmpty(clientSecret))
throw new ArgumentNullException("clientSecret");
if (string.IsNullOrEmpty(userName))
throw new ArgumentNullException("userName");
// 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.DriveReadonly }; //View the files in your Google Drive
var credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
credPath = System.IO.Path.Combine(credPath, ".credentials/apiName");
// Requesting Authentication or loading previously stored authentication for userName
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
, scopes
, userName
, System.Threading.CancellationToken.None
, new FileDataStore(credPath, true)).Result;
// Returning the SheetsService
return new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive Oauth2 Authentication Sample"
});
}
catch (Exception ex)
{
Console.WriteLine("Create Oauth2 account DriveService failed" + ex.Message);
throw new Exception("CreateServiceAccountDriveFailed", ex);
}
}
public class FilesListOptionalParms
{
/// The source of files to list.
public string Corpus { get; set; }
/// A comma-separated list of sort keys. Valid keys are 'createdTime', 'folder', 'modifiedByMeTime', 'modifiedTime', 'name', 'quotaBytesUsed', 'recency', 'sharedWithMeTime', 'starred', and 'viewedByMeTime'. Each key sorts ascending by default, but may be reversed with the 'desc' modifier. Example usage: ?orderBy=folder,modifiedTime desc,name. Please note that there is a current limitation for users with approximately one million files in which the requested sort order is ignored.
public string OrderBy { get; set; }
/// The maximum number of files to return per page.
public int PageSize { get; set; }
/// The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response.
public string PageToken { get; set; }
/// A query for filtering the file results. See the "Search for Files" guide for supported syntax.
public string Q { get; set; }
/// A comma-separated list of spaces to query within the corpus. Supported values are 'drive', 'appDataFolder' and 'photos'.
public string Spaces { get; set; }
}
public static Google.Apis.Drive.v3.Data.FileList ListAll(DriveService service, FilesListOptionalParms optional = null)
{
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
// Building the initial request.
var request = service.Files.List();
request.PageSize = 100;
//request.Fields = "nextPageToken, files(id,name,size,description,createdTime,webViewLink)";
// Applying optional parameters to the request.
request = (FilesResource.ListRequest)SampleHelpers.ApplyOptionalParms(request, optional);
var pageStreamer = new Google.Apis.Requests.PageStreamer<Google.Apis.Drive.v3.Data.File, FilesResource.ListRequest, Google.Apis.Drive.v3.Data.FileList, string>(
(req, token) => request.PageToken = token,
response => response.NextPageToken,
response => response.Files);
var allFiles = new FileList();
allFiles.Files = new List<File>();
foreach (var result in pageStreamer.Fetch(request))
{
allFiles.Files.Add(result);
}
return allFiles;
}
catch (Exception Ex)
{
throw new Exception("Request Files.List failed.", Ex);
}
}
当我尝试通过此请求询问更多信息时:
request.Fields = "nextPageToken, files(id,name,size,description,createdTime,webViewLink)";
我只有 29 个包含所有需要信息的结果(allFiles),但实际上我有 1699 个文件。当我没有指定任何字段请求时,我可以列出所有文件,但我只有 ID 和名称文件。
解决方案
推荐阅读
- android - Fragment 中的视图绑定导致 KotlinNullPointerException 在生命周期范围的协程内运行
- google-cloud-platform - Cloud Scheduler 在 10 分钟内调用了两次
- symfony4 - 无法在 symfony 中验证正确的用户名和密码
- javascript - 我在 react native 中制作应用程序,我想从 mysql 数据库中获取一些数据并将其显示在列表中?但它显示一个错误
- javascript - 通过点击带有 jQuery 的图像打开 HTML?
- spring-boot - GET /Actuator/Prometheus api 运行缓慢
- javascript - 错误类型错误:无法读取未定义的属性“audioPlayer”
- lua - 按名称从表中解压缩几个 lua 字段
- node.js - nodemon 使用带有打字稿的 express
- javascript - 如何在一个循环中获得多个 json 输出?