如何使用c#

时间:2016-04-05 10:40:38

标签: c# api google-drive-api

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

2 个答案:

答案 0 :(得分:3)

github.com/prasmussen/gdrive/

上有一个很棒的命令行可以使用谷歌驱动器

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

我已按照.NET Quickstart说明操作,然后将相关的代码从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;
        }
    }
}

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