2017-01-09 61 views
0

我可以能夠得到使用API​​直通的這個基準從谷歌驅動器中的文件:Display (View) list of files from Google Drive using Google Drive API in ASP.Net with C# and VB.Net如何獲得在C#中從谷歌雲端硬盤API的所有文件夾中的所有文件

但我只收到100條記錄。我有成千上萬的記錄。任何人都可以讓我知道要更改什麼來獲取完整的記錄顯示。

請找到下面的代碼:

namespace GoogleDrive 
{ 
    public partial class gDrive : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      GoogleConnect.ClientId = "942196220502-k107l4mtn6n606d8m38pp2k6clfmbftd.apps.googleusercontent.com"; 
      GoogleConnect.ClientSecret = "oJxTZ2Bw9QfOlrc7KgxsEf9o"; 
      GoogleConnect.RedirectUri = Request.Url.AbsoluteUri.Split('?')[0]; 
      GoogleConnect.API = EnumAPI.Drive; 
      if (!string.IsNullOrEmpty(Request.QueryString["code"])) 
      { 
       string code = Request.QueryString["code"]; 
       string json = GoogleConnect.Fetch("me", code); 
       GoogleDriveFiles files = new JavaScriptSerializer().Deserialize<GoogleDriveFiles>(json); 
       gv1.DataSource = files.Items.Where(i => i.Labels.Trashed == false); 
       gv1.DataBind(); 
      } 
      else if (Request.QueryString["error"] == "access_denied") 
      { 
       ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('Access denied.')", true); 
      } 
      else 
      { 
       GoogleConnect.Authorize("https://www.googleapis.com/auth/drive.readonly"); 
      } 
     } 

     public class GoogleDriveFiles 
     { 
      public List<GoogleDriveFile> Items { get; set; } 
     } 

     public class GoogleDriveFile 
     { 
      public string Id { get; set; } 
      public string Title { get; set; } 
      public string OriginalFilename { get; set; } 
      public string ThumbnailLink { get; set; } 
      public string IconLink { get; set; } 
      public string WebContentLink { get; set; } 
      public DateTime CreatedDate { get; set; } 
      public DateTime ModifiedDate { get; set; } 
      public GoogleDriveFileLabel Labels { get; set; } 
      public string alternateLink { get; set; } 
      public Boolean editable { get; set; } 
     } 

     public class GoogleDriveFileLabel 
     { 
      public bool Starred { get; set; } 
      public bool Hidden { get; set; } 
      public bool Trashed { get; set; } 
      public bool Restricted { get; set; } 
      public bool Viewed { get; set; } 
     } 
    } 
} 

下面的代碼適用於拿到第1000條記錄。

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(); 
    } 
    } 
} 
+0

[這個例子頁面(https://開頭開發商。 google.com/drive/v3/web/quickstart/dotnet)顯示:'listRequest.PageSize = 10;',閱讀[here](https://developers.google.com/drive/v3/reference/files/list)我們看到默認值爲100,就像您看到的一樣。您可以將其設置爲1,000,如第二頁所示。您顯然必須使用'pageToken'參數在1,000之後繼續獲取文件。向我們展示您的代碼而不是另一個頁面的鏈接會更有幫助。 – Quantic

+0

@quantic增加了編碼,請找到它 – Aruna

+0

對不起,我不知道谷歌驅動器的API或如何使用它。也許你應該遵循我鏈接的例子,而不是你發現的例子,因爲我的更新和谷歌本身。將'ClientId'和'ClientSecret'留在帖子裏是否安全? – Quantic

回答

2

您似乎正在使用Google Drive api V2。如果將maxResults參數設置爲1000,則會返回前1000行。如果還有其他行,則返回page Token作爲響應的一部分。您需要發送另一個請求並將pageToken添加到新請求中,這將返回下一次發送的數據。我對這個庫不熟悉,所以不能幫你修改代碼。

注意:您遵循本教程是從2014年起,它不使用Google Drive API which is V3的最反感的版本。你也沒有使用官方Google .Net client library

更新:

這是我列出Google Drive API的所有文件方法。它顯示瞭如何創建頁面拖放器並返回所有文件的完整列表。注意:它會繼續請求數據,直到您的谷歌驅動器上沒有更多數據。我不負責吃你的配額:)

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; } 

    } 

    /// <summary> 
    /// Lists or searches files. 
    /// Documentation https://developers.google.com/drive/v3/reference/files/list 
    /// Generation Note: This does not always build correctly. Google needs to standardize things I need to figure out which ones are wrong. 
    /// </summary> 
    /// <param name="service">Authenticated Drive service. </param> 
    /// <param name="optional">The optional parameters. </param>   
    /// <returns>FileListResponse</returns> 
    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(); 

      // 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 Google.Apis.Drive.v3.Data.FileList(); 
      allFiles.Files = new List<Google.Apis.Drive.v3.Data.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); 
     } 
    } 

可選PARMS從我的項目撕開:Unofficial Drive sample 列出所有文件從我的要點撕開:gist

+0

謝謝@dalmto,更新了api v3,但我只有1000條記錄,我怎樣才能得到剩餘的記錄。請澄清。在此鏈接上發佈了一個新問題 - http://stackoverflow.com/questions/41572228/how-to-list-of-more-than-1000-records-from-google-drive-api-v3-in-c-銳 – Aruna

+0

我有分頁一些示例代碼,我會看看我能找到它,你 – DaImTo

+0

哇大dalmto,希望那些代碼... – Aruna

相關問題