如何使用c#从google驱动器api获取文件夹的完整路径

问题描述 投票:2回答:2

如何使用google drive api c#获取文件夹的完整路径。假设我想要一个填充了Folder类的.net列表,而Folder是一个具有2个属性的类。 URL和文件夹名称。如果这个问题不好/愚蠢的话,我很新闻。任何事情都会有所帮助。

c# api google-drive-sdk
2个回答
3
投票

github.com/prasmussen/gdrive/上有一个很棒的命令行可以使用谷歌驱动器

该代码库中存在逻辑,用于从每个文件向上遍历目录树并构造完整路径。

我遵循了.NET Quickstart指令,然后将相关的go-lang代码从path.go转换为下面的C#等价物。

using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;

namespace DriveQuickstart
{
    class Program
    {
        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/drive-dotnet-quickstart.json
        static string[] Scopes = { DriveService.Scope.DriveReadonly };
        static string ApplicationName = "Drive API .NET Quickstart";
        static DriveService service;
        static Dictionary<string, Google.Apis.Drive.v3.Data.File> files = new Dictionary<string, Google.Apis.Drive.v3.Data.File>();

        static void Main(string[] args)
        {
            UserCredential credential;

            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.
            service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

            // Define parameters of request.
            FilesResource.ListRequest listRequest = service.Files.List();
            listRequest.PageSize = 10;
            listRequest.Fields = "nextPageToken, files(id, name, parents)";

            // List files.
            IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
                .Files;
            Console.WriteLine("Files:");
            if (files != null && files.Count > 0)
            {
                foreach (var file in files)
                {
                    var absPath = AbsPath(file);
                    Console.WriteLine("{0} ({1})", absPath, file.Id);
                }
            }
            else
            {
                Console.WriteLine("No files found.");
            }
            Console.Read();

        }

        private static object AbsPath(Google.Apis.Drive.v3.Data.File file)
        {
            var name = file.Name;

            if (file.Parents.Count() == 0)
            {
                return name;
            }

            var path = new List<string>();

            while (true)
            {
                var parent = GetParent(file.Parents[0]);

                // Stop when we find the root dir
                if (parent.Parents == null || parent.Parents.Count() == 0)
                {
                    break;
                }

                path.Insert(0, parent.Name);
                file = parent;
            }
            path.Add(name);
            return path.Aggregate((current, next) => Path.Combine(current, next));
        }

        private static Google.Apis.Drive.v3.Data.File GetParent(string id)
        {
            // Check cache
            if (files.ContainsKey(id))
            {
                return files[id];
            }

            // Fetch file from drive
            var request = service.Files.Get(id);
            request.Fields = "name,parents";
            var parent = request.Execute();

            // Save in cache
            files[id] = parent;

            return parent;
        }
    }
}

0
投票

文件夹和文件都被视为Google云端硬盘中的文件,因此以下代码适用于这两种方案。

创建一个函数以返回完整路径和同一任务中所需的另外两个函数:

private IList<string> GetFullPath(Google.Apis.Drive.v3.Data.File file, IList<Google.Apis.Drive.v3.Data.File> files)
        {
            IList<string> Path = new List<string>();

            if (file.Parents == null || file.Parents.Count == 0)
            {
                return Path;
            }
            Google.Apis.Drive.v3.Data.File Mainfile = file;

            while (GetParentFromID(file.Parents[0], files) != null)
            {
                Path.Add(GetFolderNameFromID(GetParentFromID(file.Parents[0], files).Id, files));
                file = GetParentFromID(file.Parents[0], files);
            }
            return Path;
        }

private Google.Apis.Drive.v3.Data.File GetParentFromID(string FileID, IList<Google.Apis.Drive.v3.Data.File> files)
        {
            if (files != null && files.Count > 0)
            {
                foreach (var file in files)
                {
                    if (file.Parents != null && file.Parents.Count > 0)
                    {
                        if (file.Id == FileID)
                        {
                            return file;
                        }
                    }
                }
            }
            return null;
        }

private string GetFolderNameFromID(string FolderID, IList<Google.Apis.Drive.v3.Data.File> files)
        {
            string FolderName = "";
            if (files != null && files.Count > 0)
            {
                foreach (var file in files)
                {
                    if (file.Id == FolderID)
                    {
                        FolderName = file.Name;
                    }
                }
            }
            return FolderName;
        }

现在您可以将该函数称为:

string Path = "My Drive";
                        foreach (string Item in GetFullPath(file, files).Reverse())
                        {
                            Path += " / " + Item;
                        }

这里传递了两个参数 - 1. file - 它是您尝试查找其路径的文件。 2. files - 驱动器上的文件列表。

© www.soinside.com 2019 - 2024. All rights reserved.