2016-04-15 137 views
0

我试图从我的Google Drive查询前10个文件的列表。随着文件,我想要得到它所在的目录...从Google Drive获取所有文件(和父文件夹)的列表

有一定要有一个更好的方式来做我所追求的。目前,我打电话给FindFiles(),该函数调用GetDriveObjectParentPath()来获取每个文件的父路径。由于GetDriveObjectParentPath()中的循环在它自己调用时遇到了User Rate Limit Exceeded [403]错误!

有人可以告诉我一个更好的方式来做我以后的一个完整的例子吗?

private string GetDriveObjectParentPath(DriveService drive, string objectId, bool digging = false) 
{ 
    string parentPath = ""; 

    FilesResource.GetRequest request = drive.Files.Get(objectId); 
    request.Fields = "id, name, parents"; 
    Google.Apis.Drive.v3.Data.File driveObject = request.Execute(); 

    if (digging) 
     parentPath += "/" + driveObject.Name; 

    if (driveObject.Parents != null) 
     parentPath = GetDriveObjectParentPath(drive, driveObject.Parents[0], true) + parentPath; 

    return parentPath; 
} 

private bool FindFiles() 
{ 
    //Setup the API drive service 
    DriveService drive = new DriveService(new BaseClientService.Initializer() 
    { 
     HttpClientInitializer = m_credentials, 
     ApplicationName = System.AppDomain.CurrentDomain.FriendlyName, 
    }); 

    //Setup the parameters of the request 
    FilesResource.ListRequest request = drive.Files.List(); 
    request.PageSize = 10; 
    request.Fields = "nextPageToken, files(mimeType, id, name, parents)"; 

    //List first 10 files 
    IList<Google.Apis.Drive.v3.Data.File> files = request.Execute().Files; 
    if (files != null && files.Count > 0) 
    { 
     foreach (Google.Apis.Drive.v3.Data.File file in files) 
     { 
      Console.WriteLine("{0} ({1})", file.Name, file.Id); 

      string parentPath = GetDriveObjectParentPath(drive, file.Id); 

      Console.WriteLine("Found file '" + file.Name + "' that is in directory '" + parentPath + "' and has an id of '" + file.Id + "'."); 
     } 
    } 
    else 
    { 
     Console.WriteLine("No files found."); 
    } 

    Console.WriteLine("Op completed."); 
    return true; 
} 

使用上面产生一个单一的运行,并在403客户端错误结果如下API使用... enter image description here

回答

1

你的代码是罚款的。您只需要更慢地处理403速率限制并重试。我知道它很糟糕,但这就是Drive的工作原理。

我通常会在30个左右的请求后看到403个速率限制错误,以便符合您的观察。

就方法而言,无论何时我看到一个包含“文件夹层次结构”的问题,我的建议都是一样的。首先使用files.list提取所有文件夹:mimetype ='application/vnd.google-apps.folder'。然后处理该列表一次以构建内存中的层次结构。然后去抓取你的文件并在层次结构中找到它们。请记住,在GDrive中,“层次结构”有些虚构,因为父母只是任何给定文件/文件夹的属性。这意味着文件/文件夹可以有多个父母,并且层次甚至可以循环回去。

+0

我更新了问题以显示使用情况结果。请记住,这不仅仅是10个请求。这是最初请求获得所有文件的1,然后每个父母都是1。所以如果第一个文件位于'/我的驱动器/我的第一个文件夹/第二个/和最终文件夹/我的file.txt',这将导致4个请求总共5个JUST来获取第一个文件的信息。这就是为什么我希望我可以做一些不同的事情来获得每个文件的完整路径,而不是提交数百个请求来获得如此简单的结果。 –

+0

Gotcha。我已经更新了一些附加信息的答案。无论采取什么方法,403速率限制都是GDrive生活的一个不幸事实,因此您需要在代码中处理它们。 – pinoyyid

+0

啊,这是一个好主意!请求获取应用程序本地列表中的所有“文件夹”,然后请求获取应用程序本地列表中的所有“文件”。做所有的比较和检查内部的应用程序,而不是一堆查询! ;) –

相关问题