Search code examples
c#winformsmicrosoft-graph-apionedrivemicrosoft-graph-sdks

Fetch all the folders in OneDrive using Microsoft graph API


I am trying to fetch all the folders in Onedrive(not files) using graph api. I am looking for query similar to the below query:

var folders=await client.Me.Drive.Root.Children.Request().GetAsync();

The above query fetches both files and folders and I am looking for folders only.

Thanks in advance.


Solution

  • To get only the folders in the group there is a property called 'Folder' in every drivenItem object which can be used to detect if that particular drivenItem object is a file or a folder. If that object is Folder then the value in it won't be null. If it is a file then definitely the Folder property is null.

    public static async Task<IEnumerable<DriveItem>> GetOnlyFolders()
    {
          var folders = await graphClient.Me.Drive.Root.Children
          .Request()
          .GetAsync();
    
           return folders.CurrentPage;
    }
    static void OnlyFolders()
    {
          var result = GraphHelper.GetOnlyFolders().Result;
          foreach (var item in result)
          {
              if(item.Folder != null)
              {
                   Console.WriteLine(item.Name);
              }
          }
    }
    

    Tested it in my application and resulted as below.

    My OneDrive:- Please click this link to see my one drive

    My Application after applying the code:- Please click this link to view the folders