Use the OneDrive API without user interaction, such as a batch program (.NET C# version) (using the Microsoft Graph library)

Page update date :
Page creation date :

Operating environment

Visual Studio
  • Visual Studio 2022
.NET
  • .NET 8
Microsoft Authentication API
  • 2.0 OAuth 2
Microsoft OneDrive API
  • 1.0
Microsoft.Graph
  • 5.54.0
Types of Microsoft accounts
  • Work or school account

Prerequisites

Visual Studio
  • One of the versions
.NET
  • One of the versions
Microsoft Authentication API
  • 2.0 OAuth 2
Microsoft OneDrive API
  • 1.0
Microsoft.Graph
  • 5.XX
Types of Microsoft accounts
  • Work or school account

About this tip

This Tip is a modified program using the library based on Microsoft Graph the following Tips. Therefore, please refer to the following tips procedure for an overview and operation procedure on Azure, and refer to this tip when you build the program.

precondition

  • You have a Microsoft account for a work or school account
  • You can use the OneDrive associated with the Microsoft account listed above (e.g., OneDrive Business)
  • Visual Studio 2022 installed
  • You have registered your app on Azure by referring to the tips above and obtained the necessary information such as ID.

Create a console application

Start Visual Studio and create a project for your console application. You can create it outside of Visual Studio, but I'll use Visual Studio for now.

The location and project name are optional. In this case, the project name is OneDriveApiDotNetClientCredentialsMicrosoftGraph .

Microsoft.Graph First, get the and Azure.Identity libraries from NuGet.

This time, we will not divide the code, but Program.cs will write it staggered from the top, so if you can check the movement, please rewrite it by dividing the code as necessary.

using Azure.Identity;
using Microsoft.Graph;

Describe the namespace you want to use.

// 各種 ID などの定義
var clientId = "XXXXXXXX";      // クライアント ID
var tenantId = "XXXXXXXX";      // テナント ID
var clientSecret = "XXXXXXXX";  // クライアント シークレット
var userId = "XXXXXXXX";        // ユーザー ID

Set the ID obtained on Azure for each.

// 使いまわすので最初に定義しておく
HttpClient httpClient = new();

You have generated a to make a request to HttpClient the specified URL.

// クライアント シークレットによる認証情報を定義
ClientSecretCredential clientSecretCredential = new(tenantId, clientId, clientSecret);

// HttpClient と認証情報で Microsoft Graph サービスのクライアントを生成
using GraphServiceClient graphClient = new(httpClient, clientSecretCredential);

Define the client secret using the ID you obtained, and so on. You can use that data to HttpClient GraphServiceClient create an instance of . This is GraphServiceClient often used to access various APIs.

// 対象ユーザーに紐づく OneDrive を取得 (紐づいているドライブが OneDrive 1つという前提)
var drive = await graphClient.Users[userId].Drive.GetAsync();
if (drive == null)
{
  Console.WriteLine("ドライブを取得できませんでした。");
  return;
}

GraphServiceClient to get the OneDrive associated with the user first. If you have multiple drives linked, Drives find and retrieve the target OneDrive from . It's possible that a drive other than OneDrive is also linked, but I haven't checked that much. If you are sure that only one OneDrive is linked, you Drive can get it as it is in the properties.

// OneDrive のルートを取得
var root = await graphClient.Drives[drive.Id].Root.GetAsync();
if (root == null)
{
  Console.WriteLine("OneDrive のルートを取得できませんでした。");
  return;
}

Once you have OneDrive, you can access it freely. If you are looking up the ID of a folder or file, you can specify it directly. First of all, I haven't checked anything, so I'm getting the root folder.

// ルート直下にあるフォルダ一覧取得
var rootChildren = await graphClient.Drives[drive.Id].Items[root.Id].Children.GetAsync();
if (rootChildren == null || rootChildren.Value == null)
{
  Console.WriteLine("フォルダの一覧を取得できませんでした。");
  return;
}
foreach (var item in rootChildren.Value)
{
  Console.WriteLine($"Type={(item.File != null ? "File" : "Folder")}, Id={item.Id}, Name={item.Name}, Size={item.Size}");
}

Once you have the root folder, Children you can get a list of files and folders directly under it. After that, I enumerate the retrieved values and display the names.

Summary

I tried to write code using the library of "Microsoft Graph". I think you can reduce the amount of code considerably compared to accessing the URL of the API.

However, I think the disadvantages are that different versions of the library can cause breaking changes to the code and there is little documentation. If you can tolerate these, I think it would be more advantageous to reduce the amount of code you write.

thanks

I had some questions about using the OneDrive API this time, so I asked a question.