【问题标题】:how do i get a full path of a folder from google drive api with c#如何使用 c# 从 google drive api 获取文件夹的完整路径
【发布时间】:2016-04-05 10:40:37
【问题描述】:

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

【问题讨论】:

标签: c# api google-drive-api


【解决方案1】:

github.com/prasmussen/gdrive/ 上提供了一个用于使用 google drive 的出色命令行

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

我已按照.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;
        }
    }
}

【讨论】:

    【解决方案2】:

    文件夹和文件都被视为 Google Drive 中的文件,因此以下代码适用于这两种情况。

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

    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. 文件 - 这是您要查找其路径的文件。 2. files - 驱动器上的文件列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      • 2020-08-09
      • 2011-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多