2017-01-09 20 views
0

APIを使用してGoogleドライブからファイルを取得するには、Display (View) list of files from Google Drive using Google Drive API in ASP.Net with C# and VB.Netの参照を使用できます。CドライブのGoogleドライブ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;'、[ここ](https://developers.google.com/drive/v3/reference/files/list)私たちはあなたが見ているようにデフォルトが100であることを見ます。その2番目のページに示されているように1,000まで設定できます。あなたは明らかに、何らかの理由で 'pageToken'パラメータを使用して1,000を超えてファイルを取得し続ける必要があります。別のページへのリンクの代わりにコードを表示すると、より便利になります。 – Quantic

+0

@quanticコーディングが追加されました、plsが見つかりました – Aruna

+0

申し訳ありませんGoogleドライブのAPIまたはその使用方法がわかりません。あなたが見つけたものの代わりに、私がリンクしている例に従うべきでしょう。あなたのポストに 'ClientId'と' ClientSecret'を残しても安全ですか? – Quantic

答えて

2

あなたはGoogleドライブAPI V2を使用しているようです。 maxResultsパラメータを1000に設定すると、最初の1000行が返されます。追加行がある場合は、応答の一部としてpage Tokenが返されます。別のリクエストを送信し、新しいリクエストにpageTokenを追加する必要があります。これにより、次に送られたデータが返されます。私はそのライブラリに慣れていないので、コードを変更するのに役立ちません。

注:あなたが従うチュートリアルは2014年のものであり、最も再送信されたバージョンのGoogle Drive API which is V3は使用していません。また、あなたは公式Google .Net client libraryを使用していません。

更新:

これは、GoogleドライブAPIのすべてのファイルのリストです。ページストリーマーを作成する方法を示し、すべてのファイルの完全なリストを返します。注:Googleドライブにデータがなくなるまでデータのリクエストを続けます。私はあなたのクォータを食べるための責任を負いませんよ:)

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レコードしか得られませんでした。 plsは明らかにする。このリンクに新しい質問が投稿されました - http://stackoverflow.com/questions/41572228/how-to-list-of-more-than-1000-records-from-google-drive-api-v3-in-c-鋭い – Aruna

+0

私はページ設定のサンプルコードをいくつか持っています。もし私があなたのために見つけることができるのであれば、 – DaImTo

+0

これらのコードを期待してwow great dalmto ... – Aruna

関連する問題