如何在C#中列出来自Google Drive API V3的1000多条记录

时间:2017-01-10 15:20:53

标签: c# api google-api google-drive-realtime-api

这是此link中原始问题的延续。

通过以下代码,我可以获取1000条记录,但我的驱动器总共有6500条++记录。搜索谷歌但无法找到正确的解决方案。

根据参考,参数“pageSize”的描述值是“每页返回的最大文件数。可接受的值为1到1000,包括端值。(默认值:100)”。

所以这意味着,我们只能获得1000条记录,如果可能,那么方式是什么。另外,我不了解参数“pageToken”,实时使用'nextPageToken'值是什么。

代码:(https://developers.google.com/drive/v3/web/quickstart/dotnet

namespace gDrive
{
    class Program
    {
        static string[] Scopes = { DriveService.Scope.DriveReadonly };
        static string ApplicationName = "Drive API .NET Quickstart";

    static void Main(string[] args)
    {
        UserCredential credential;
        gDriveTableAdapter gDrive = new gDriveTableAdapter();

        using (var stream =
            new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
        {
            string credPath = System.Environment.GetFolderPath(
                System.Environment.SpecialFolder.Personal);
            credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");

            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(credPath, true)).Result;
            //Console.WriteLine("Credential file saved to: " + credPath);
        }

        // Create Drive API service.
        var service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName,
        });

        // Define parameters of request.
        FilesResource.ListRequest listRequest = service.Files.List();
        listRequest.PageSize = 1000;
        listRequest.Fields = "nextPageToken, files(webViewLink, name)";

        // List files.
        IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
            .Files;
        Console.WriteLine("Processing...\n");
        if (files != null && files.Count > 0)
        {
            foreach (var file in files)
            {
                gDrive.InsertQuery(file.Name, file.WebViewLink);
            }
            Console.WriteLine(files.Count + " records fetched.");
        }
        else
        {
            Console.WriteLine("No files found.");
        }
        Console.Read();
    }
  }
}

4 个答案:

答案 0 :(得分:6)

如果您需要下载分页,您也可以通过C#SDK实现。 诀窍是跟踪 listRequest.Execute()返回值,它包含几个变量,并且它们之间是NextPageToken。这部分是&#34;隐藏&#34;在standard google example

FilesResource.ListRequest listRequest = _service.Files.List();
listRequest.PageSize = 100;
listRequest.Fields = "nextPageToken, files(id, name)";

// List files.
var result =  listRequest.Execute();
IList<Google.Apis.Drive.v3.Data.File> files =result.Files;
Console.WriteLine("Files:");
while (files!=null && files.Count > 0)
{
    foreach (var file in files)
    {
        Console.WriteLine("{0} ({1})", file.Name, file.Id);
    }
    if (!string.IsNullOrWhiteSpace(result.NextPageToken))
    {
        listRequest = _service.Files.List();
        listRequest.PageToken = result.NextPageToken;
        listRequest.PageSize = 100;
        listRequest.Fields = "nextPageToken, files(id, name)";
        result = listRequest.Execute();
        files = result.Files;
    }
}

答案 1 :(得分:1)

您可以发出多个请求并从每个页面获取数据。根据安全原因将这些项目放在页面上

答案 2 :(得分:1)

通过Google Script实现。感谢mesgarpour(link)。

var folderId = "Enter the Folder Id here";

// Main function 1: List all folders, & write into the current sheet.
function listFolders(){
  getFolderTree(folderId, false);
};

// Main function 2: List all files & folders, & write into the current sheet.
function listAll(){
  getFolderTree(folderId, true); 
};

// =================
// Get Folder Tree
function getFolderTree(folderId, listAll) {
  try {
    // If you want to search from the top (root) folder
    var parentFolder = DriveApp.getRootFolder();

    // If you want a tree of any sub folder
    //var parentFolder = DriveApp.getFolderById(folderId);

    // Initialise the sheet
    var file, data, sheet = SpreadsheetApp.getActiveSheet();
    sheet.clear();
    sheet.appendRow(["Full Path", "Name", "Date", "URL", "Last Updated", "Description", "Size"]);

    // Get files and folders
    getChildFolders(parentFolder.getName(), parentFolder, data, sheet, listAll);

  } catch (e) {
    Logger.log(e.toString());
  }
};

// Get the list of files and folders and their metadata in recursive mode
function getChildFolders(parentName, parent, data, sheet, listAll) {
  var childFolders = parent.getFolders();

  // List folders inside the folder
  while (childFolders.hasNext()) {
    var childFolder = childFolders.next();
    // Logger.log("Folder Name: " + childFolder.getName());
    data = [ 
      parentName + "/" + childFolder.getName(),
      childFolder.getName(),
      childFolder.getDateCreated(),
      childFolder.getUrl(),
      childFolder.getLastUpdated(),
      childFolder.getDescription(),
      childFolder.getSize()
    ];
    // Write
    sheet.appendRow(data);

    // List files inside the folder
    var files = childFolder.getFiles();
    while (listAll & files.hasNext()) {
      var childFile = files.next();
      // Logger.log("File Name: " + childFile.getName());
      data = [ 
        parentName + "/" + childFolder.getName() + "/" + childFile.getName(),
        childFile.getName(),
        childFile.getDateCreated(),
        childFile.getUrl(),
        childFile.getLastUpdated(),
        childFile.getDescription(),
        childFile.getSize()
      ];
      // Write
      sheet.appendRow(data);
    }

    // Recursive call of the subfolder
    getChildFolders(parentName + "/" + childFolder.getName(), childFolder, data, sheet, listAll);  
  }
};

答案 3 :(得分:1)

以下是EDR的改进(IMO)版本的重要答案,不重复listRequest代码:

.hidegalimage {
display:none;
}