2

how do i get a full path of a folder with google drive api c#. Lets say i want a .net list filled with Folder class and Folder being a class with 2 properties. URL and folder name. Iam new to this so sorry if the question is bad/dumb. Any thing would help at this point.

Robel Haile
  • 309
  • 1
  • 5
  • 18
  • This might answers your question http://stackoverflow.com/questions/10345381/get-post-requests-google-drive-api – Shrutika Kalra Apr 05 '16 at 10:45
  • I would create a while loop as long as it has parents and just keep doing a file.get on that new parent eventually you will run out of parents and can build your directory name up that way. – Linda Lawton - DaImTo Apr 05 '16 at 11:44
  • 1
    Possible duplicate of [Google Drive Api - Get Folder Paths](http://stackoverflow.com/questions/13709755/google-drive-api-get-folder-paths) – AL. Apr 05 '16 at 22:32

2 Answers2

6

There is a fantastic command line for working with google drive available on github.com/prasmussen/gdrive/

The logic exists in that codebase to walk the directory tree up from each file and construct the full path.

I've followed the .NET Quickstart instructions, then converted the relevant go-lang code from path.go into the C# equivalent below.

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;
        }
    }
}
Don Vince
  • 1,282
  • 3
  • 18
  • 28
0

Folder and Files both are considered as a File in Google Drive hence the following code will work for both the scenarios.

Create a function to return Full Path and Two other functions required in the same Task :

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

Now you may call the function as :

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

here, two parameters are passed - 1. file - it is the file whose path you are trying to find. 2. files - the list of files on your drive.