2016-04-15 135 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

啊,這是一個好主意!請求獲取應用程序本地列表中的所有「文件夾」,然後請求獲取應用程序本地列表中的所有「文件」。做所有的比較和檢查內部的應用程序,而不是一堆查詢! ;) –

相關問題