【问题标题】:How to get all files from all folders from Google Drive API in C#如何从 C# 中的 Google Drive API 获取所有文件夹中的所有文件
【发布时间】:2017-01-09 21:22:56
【问题描述】:

我可以通过以下引用使用 API 从 Google Drive 获取文件:Display (View) list of files from Google Drive using Google Drive API in ASP.Net with C# and VB.Net

但我只得到 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();
    }
  }
}

【问题讨论】:

  • This example page 显示:listRequest.PageSize = 10;,阅读 here 我们看到默认值为 100,就像您看到的那样。如第二页所示,您可以将其设置为 1,000。您显然必须以某种方式使用pageToken 参数才能在 1,000 之后继续获取文件。向我们展示您的代码而不是指向另一个页面的链接会更有帮助。
  • @quantic添加编码,请找到
  • 对不起,我不知道 google drive 的 API 或如何使用它。也许您应该遵循我链接的示例而不是您找到的示例,因为我的示例较新并且来自谷歌本身。在您的帖子中留下ClientIdClientSecret 是否安全?
  • 它只是一个测试文件,所以没有问题
  • 在此链接上发布了一个新问题 - stackoverflow.com/questions/41572228/…

标签: c# asp.net .net google-api google-drive-api


【解决方案1】:

您似乎正在使用 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);
        }
    }

从我的项目中提取的可选参数:Unofficial Drive sample 列出从我的 gist 中提取的所有文件:gist

【讨论】:

  • 感谢@dalmto,更新了 api v3 但我只得到了 1000 条记录,我怎样才能得到剩余的记录。请澄清。在此链接上发布了一个新问题 - stackoverflow.com/questions/41572228/…
  • 我有一些带分页的示例代码,我看看能不能帮你找到
  • 如果您发现此代码有用并认为它应该成为我的非官方驱动示例项目的一部分,我将不胜感激。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多