C# Google Drive SDK. 如何获取Google Drive文件夹列表?

3
我正在编写一个程序,允许用户上传文件到他们的Google Drive帐户。我已经实现了上传部分,并使用OAuth2。我目前遇到的问题是从用户的Drive帐户获取文件夹列表。
我找到了一些代码,据说可以使用.setUserCredentials方法来实现,但它不起作用:
DocumentsService service1 = new DocumentsService("project");            
        service1.setUserCredentials("user","pass");

        FolderQuery query1 = new FolderQuery();

        // Make a request to the API and get all documents.
        DocumentsFeed feed = service1.Query(query1);

        // Iterate through all of the documents returned
        foreach (DocumentEntry entry in feed.Entries)
        {
            var blech = entry.Title.Text;
        }

没有返回任何内容。理想情况下,我希望使用OAuth2来完成这个任务。我一直在尝试以下代码,试图设置身份验证令牌,但我总是被拒绝访问:

String CLIENT_ID = "clientid";
String CLIENT_SECRET = "secretid";

var docprovider = new NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET);
var docstate = GetDocAuthentication(docprovider);

DocumentsService service1 = new DocumentsService("project");

service1.SetAuthenticationToken(docstate.RefreshToken);
FolderQuery query1 = new FolderQuery();

DocumentsFeed feed = service1.Query(query1); //get error here

        // Iterate through all of the documents returned
        foreach (DocumentEntry entry in feed.Entries)
        {
            // Print the title of this document to the screen
            var blech = entry.Title.Text;
        }

..

    private static IAuthorizationState GetDocAuthentication(NativeApplicationClient client)
    {
        const string STORAGE = "storagestring";
        const string KEY = "keystring";
        string scope = "https://docs.google.com/feeds/default/private/full/-/folder";            
        // Check if there is a cached refresh token available.
        IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY);
        if (state != null)
        {
            try
            {
                client.RefreshToken(state);
                return state; // Yes - we are done.
            }
            catch (DotNetOpenAuth.Messaging.ProtocolException ex)
            {

            }
        }

        // Retrieve the authorization from the user.
        state = AuthorizationMgr.RequestNativeAuthorization(client, scope);
        AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state);
        return state;
    }

具体而言,我得到了“执行请求失败:https://docs.google.com/feeds/default/private/full/-/folder - 远程服务器返回错误:(401) 未经授权"。
我还尝试过:
var docauth = new OAuth2Authenticator<NativeApplicationClient>(docprovider, GetDocAuthentication);
DocumentsService service1 = new DocumentsService("project");
service1.SetAuthenticationToken(docauth.State.AccessToken);

但是,“State”始终为空,所以我会得到一个空对象错误。我做错了什么?应该怎么做呢?
4个回答

4
你应该使用Drive SDK而不是Documents List API,它允许你列出文件夹。如果你想要列出根目录,可以使用"root"作为folderId。

谢谢,但是我怎么判断一个文件是文件夹还是文件呢?使用链接中的代码,我获得了'root'下的子项目,但是我不知道如何区分它们是文件还是文件夹,因为它似乎同时返回了文件和文件夹。 - ygetarts
4
好的,没关系,我想我明白了。我只需要设置请求的q参数为"mimeType='application/vnd.google-apps.folder'",这将只返回文件夹。感谢您的帮助。 - ygetarts

2

我实际上已经为.NET实现了GDrive SDK的v3版本,并且也需要搜索文件夹。

我更喜欢独立请求所有文件夹,而不是获取所有文件,然后执行LinQ查询以仅保留文件夹。

这是我的实现方式:

Original Answer 翻译成“最初的回答”

private async Task<bool> FolderExistsAsync(string folderName)
{
    var response = await GetAllFoldersAsync();
    return response.Files
                   .Where(x => x.Name.ToLower() == folderName.ToLower())
                   .Any();
}

private async Task<Google.Apis.Drive.v3.Data.FileList> GetAllFoldersAsync()
{
    var request = _service.Files.List();
    request.Q = "mimeType = 'application/vnd.google-apps.folder'";
    var response = await request.ExecuteAsync();
    return response;
}

你也可以这样请求Q的名称:“最初的回答”。
request.Q = $"mimeType = 'application/vnd.google-apps.folder' and name = '{folderName}'";

这会导致并简化事情(避免null检查): "最初的回答"。
private async Task<bool> FolderExistsAsync(string folderName)
{
    var response = await GetDesiredFolder(folderName);
    return response.Files.Any();
}

private async Task<FileList> GetDesiredFolder(string folderName)
{
    var request = _service.Files.List();
    request.Q = $"mimeType = 'application/vnd.google-apps.folder' and name = '{folderName}'";
    var response = await request.ExecuteAsync();
    return response;
}

0

我找到了一种从谷歌云盘获取文件夹列表的方法

  FilesResource.ListRequest filelist= service.Files.List();
  filelist.Execute().Items.ToList().Where(x => x.MimeType == "application/vnd.google-apps.folder").ToList()

0
private IEnumerable<DocumentEntry> GetFolders(string id) {
    if (IsLogged) {
        var query = new FolderQuery(id)
        {
            ShowFolders = true
        };

        var feed = GoogleDocumentsService.Query(query);

        return feed.Entries.Cast<DocumentEntry>().Where(x => x.IsFolder).OrderBy(x => x.Title.Text);
    }

    return null;
}

    ...
var rootFolders = GetFolders("root");
if (rootFolders != null){
    foreach(var folder in rootFolders){
        var subFolders = GetFolders(folder.ResourceId);
        ...
    }
}

其中GoogleDocumentsServiceDocumentsService的实例,而IsLogged是一个表示成功登录的标志。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接