Я пытаюсь получить информацию метаданных обо всем Google Диске. Это мой код:
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 файлов. Когда я не указываю какие-либо поля в запросе, я могу перечислить все файлы, но у меня есть только идентификатор и имя файла.
Можете ли вы дать ссылку, откуда вы взяли этот код, пожалуйста?
Код взят из: gist.github.com/LindaLawton/9e512d95ef874d0c4dbc8d0783dcc4bc
@Ulixes, если вы собираетесь скопировать мой файл Gist, вы можете также прочитать написанное мной руководство, которое прилагается к нему daimto.com/list-all-files-on-google-drive





Обработка исключений - моя любимая мозоль. То, как вы повторно генерируете исключение, очистит трассировку стека, которая составляет около 90% соответствующей информации, а также добавит еще один слой. Вот две статьи о правильной обработке исключений, на которые я много ссылаюсь: blogs.msdn.microsoft.com/ericlippert/2008/09/10/… | codeproject.com/Articles/9538/…