如何从C#中Google Drive API的所有文件夹中获取所有文件 [英] How to get all files from all folders from Google Drive API in C#

查看:297
本文介绍了如何从C#中Google Drive API的所有文件夹中获取所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用API​​从Google Drive获取文件,通过以下参考:使用Google Drive API在Google Drive中显示(查看)文件列表。 Net with C#and VB.Net



但我只能得到100条记录。我有成千上万的记录。任何人都可以请让我知道要更改什么以获得完整的记录显示。



请找到下面的代码:

< pre $ 命名空间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文件= new JavaScriptSerializer()。反序列化< 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('拒绝访问。'),true);
}
else
{
GoogleConnect.Authorize(https://www.googleapis.com/auth/drive.readonly);
}
}

公共类GoogleDriveFiles
{
公开列表< GoogleDriveFile> Items {get;组; }
}

public class GoogleDriveFile
{
public string Id {get;组; }
public string Title {get;组; }
public string OriginalFilename {get;组; }
public string ThumbnailLink {get;组; }
public string IconLink {get;组; }
公共字符串WebContentLink {get;组; }
public DateTime CreatedDate {get;组; }
public DateTime ModifiedDate {get;组; }
public GoogleDriveFileLabel Labels {get;组; }
公共字符串alternateLink {get;组; }
public Boolean editable {get;组; }
}

public class GoogleDriveFileLabel
{
public bool Starred {get;组; }
public bool Hidden {get;组; }
public bool Trashed {get;组; }
public bool受限{get;组; }
public bool已浏览{get;组; }
}
}
}






以下代码适用于获取前1000条记录。

 命名空间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();

使用(var stream =
new FileStream(client_secret.json,FileMode.Open,FileAccess.Read))
{
字符串credPath = System.Environment .GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath,.credentials / drive-dotnet-quickstart.json);

凭证= GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(流).Secrets,
作用域,
用户,
CancellationToken.None,
新的FileDataStore(credPath,true))。
//Console.WriteLine(\"Credential file saved to:+ credPath);
}

//创建Drive API服务。
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer =凭证,
ApplicationName = ApplicationName,
});

//定义请求的参数。
FilesResource.ListRequest listRequest = service.Files.List();
listRequest.PageSize = 1000;
listRequest.Fields =nextPageToken,files(webViewLink,name);

//列出文件。
IList< Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
.Files;
Console.WriteLine(Processing ... \\\
);
if(files!= null&& file.Count> 0)
{
foreach(文件中的var文件)
{
gDrive.InsertQuery( file.Name,file.WebViewLink);
}
Console.WriteLine(files.Count +记录提取。);
}
else
{
Console.WriteLine(No files found。);
}
Console.Read();




解决方案

您似乎正在使用Google Drive api V2。如果将maxResults参数设置为1000,则会返回前1000行。如果还有其他行页面令牌作为响应的一部分返回。您需要发送另一个请求并将pageToken添加到新请求中,这将返回下一次发送的数据。我对该库不熟悉,因此无法帮助您更改代码。



注意:您所遵循的教程是从2014年开始的,它不使用最新版本的 V3云端硬盘API 。此外,您并未使用官方的 Google .Net客户端库

更新:

这是我列出Google Drive API的所有文件方法。它显示了如何创建页面拖放器并返回所有文件的完整列表。注意:它会继续请求数据,直到您的谷歌驱动器上没有更多数据。我不负责食用你的配额:)

  public class FilesListOptionalParms 
{
///要列出的文件的来源。
public string Corpus {get;组; }
///用逗号分隔的排序键列表。有效密钥为'createdTime','folder','modifiedByMeTime','modifiedTime','name','quotaBytesUsed','recency','sharedWithMeTime','starred'和'viewedByMeTime'。每个按键默认按升序排序,但可以使用desc修饰符反转。用法示例:?orderBy =文件夹,modifiedTime desc,名称。请注意,对于大约一百万个文件的用户而言,目前的局限性是忽略了请求的排序顺序。
公共字符串OrderBy {get;组; }
///每页返回的最大文件数量。
public int PageSize {get;组; }
///用于在下一页继续前一个列表请求的标记。这应该设置为前一个响应中的'nextPageToken'的值。
public string PageToken {get;组; }
///用于过滤文件结果的查询。有关支持的语法,请参阅搜索文件指南。
公共字符串Q {get;组; }
///在语料库中查询的空格的逗号分隔列表。支持的值有'drive','appDataFolder'和'照片'。
public string Spaces {get;组; }

}

///< summary>
///列出或搜索文件。
///文档https://developers.google.com/drive/v3/reference/files/list
///生成注意:这并不总是正确生成。谷歌需要将我需要的东西标准化,找出哪些是错误的。
///< / summary>
///< param name =service> Authenticated Drive服务。 < / PARAM>
///< param name =optional>可选参数。 < / PARAM>
///<返回> FileListResponse< / returns>
public static Google.Apis.Drive.v3.Data.FileList ListAll(DriveService服务,FilesListOptionalParms可选= null)
{
尝试
{
//初始验证。
if(service == null)
throw new ArgumentNullException(service);

//构建初始请求。
var request = service.Files.List();

//将可选参数应用于请求。
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(pageStreamer.Fetch(request)中的var结果)
{
allFiles.Files.Add(result);
}

返回allFiles;

$ b catch(Exception Ex)
{
抛出新异常(Request Files.List failed。,Ex);


从我的项目中剥离的可选参数:非官方云端硬盘示例 b $ b列出从我的要点中撕下的所有文件: gist


I can able get the files from Google Drive using API thru the reference of this: Display (View) list of files from Google Drive using Google Drive API in ASP.Net with C# and VB.Net .

But I get 100 records only. I ve some thousands of records. Can anyone please let me know what to change to get the full records display.

Please find the code below:

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


Below code is applicable to get the first 1000 records.

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

解决方案

You appear to be using the Google Drive api V2. If you send the maxResults parameter set to 1000 you will return the first 1000 rows. If there are additional rows page Token is returned as part of your response. You will need to send another request and add the pageToken to the new request this will return the next sent of data for you. I am not familiar with that library so cant help you alter the code.

Note: The tutorial you are following is from 2014 and it does not use the most resent version of the Google Drive API which is V3. Also you are not using the official Google .Net client library.

Update:

This is my list all files method for the Google Drive API. it shows how to create a page streamer and will return a full list of ALL the files. Note: it will continue requesting data until there is no more data on your google drive. I am not responsible for eating your quota :)

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

Optional parms ripped from my project: Unofficial Drive sample List all files ripped from my gist: gist

这篇关于如何从C#中Google Drive API的所有文件夹中获取所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆