OneDrive のファイル、フォルダを検索するコードを紹介します。
概要
C#のプログラムからOneDriveのファイルを検索して該当する項目やIDを取得するコードを紹介します。
事前準備
OneDriveのAPIを呼び出すプログラムを作成する前に、アプリケーションの登録や設定が必要です。
以下の準備をする必要があります。手順の詳細は
こちらの記事を参照してください。
- Azure Active Directory へのプログラム登録
- パブリック クライアント フローを有効にする
- ファイルAPIのAPIアクセス許可を追加
- APIのアクセス許可
- Microsoft.Graph ライブラリのインストール
OneDriveのファイル
OneDriveにファイルを配置します。ルートフォルダのファイルは下図の通りです。
ルートフォルダの folder1 フォルダ内のファイルは下図の通りです。
プログラム
UI
下図のフォームを作成します。
コード
以下のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Identity.Client;
using Microsoft.Graph;
namespace SimpleCallApi
{
public partial class FormSearch : Form
{
public static IPublicClientApplication PublicClientApp;
private string ClientId = "(クライアントID)";
private string TenantId = "(テナントID)";
public FormSearch()
{
InitializeComponent();
}
private async void button1_Click(object sender, EventArgs e)
{
PublicClientApplicationBuilder app = PublicClientApplicationBuilder.Create(ClientId);
app = app.WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient");
app = app.WithAuthority(AzureCloudInstance.AzurePublic, TenantId);
PublicClientApp = app.Build();
//
string[] scopes = new string[] { "User.ReadWrite.All" };
string password = "(OneDrive へのサインインIDのパスワード)";
System.Security.SecureString secpass = new System.Security.SecureString();
foreach (char c in password) secpass.AppendChar(c);
AcquireTokenByUsernamePasswordParameterBuilder builder = PublicClientApp.AcquireTokenByUsernamePassword(scopes, "(OneDrive へのサインインID)", secpass);
AuthenticationResult authResult = await builder.ExecuteAsync();
DelegateAuthenticationProvider prov = new DelegateAuthenticationProvider(
(requestMessage) =>
{
requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", authResult.AccessToken);
return Task.FromResult(0);
}
);
GraphServiceClient client = new GraphServiceClient(prov);
IDriveSearchCollectionPage items = await client.Me.Drive.Search("sound2.flac").Request().GetAsync();
foreach (DriveItem item in items) {
if (item.Folder == null) {
textBox1.Text += string.Format("{0}\t{1}\r\n", item.Name, item.Id);
}
else {
textBox1.Text += string.Format("{0}\t{1}\tフォルダ\r\n", item.Name, item.Id);
}
}
}
}
}
解説
OneDriveのライブラリの初期化やOneDriveへのサインイン、アクセストークンの取得については
こちらの記事を参照してください。
GraphServiceClient オブジェクトを取得し、GraphServiceClient オブジェクトの 'Me.Drive.Search()' メソッドを呼び出します。
第一引数に検索文字列を与えます。下記のコード例では "sound2.flac"ファイルを検索しています。
非同期処理で要素の列挙型 IDriveSearchCollectionPage を取得するために、'.Request().GetAsync()' メソッドを呼び出して取得しています。
GraphServiceClient client = new GraphServiceClient(prov);
IDriveSearchCollectionPage items = await client.Me.Drive.Search("sound2.flac").Request().GetAsync();
取得した
IDriveSearchCollectionPage
オブジェクトをforrach ループで個々の要素を取得し、テキストボックスに表示します。
ファイル名は
DriveItem
オブジェクトの
Name
プロパティで取得します。要素のIDは
DriveItem
オブジェクトの
Id
プロパティで取得します。
foreach (DriveItem item in items) {
if (item.Folder == null) {
textBox1.Text += string.Format("{0}\t{1}\r\n", item.Name, item.Id);
}
else {
textBox1.Text += string.Format("{0}\t{1}\tフォルダ\r\n", item.Name, item.Id);
}
}
実行結果
プロジェクトを実行します。カウのウィンドウが表示されます。
[button1] をクリックします。"sound2.flac" ファイルを検索します。
該当するファイルが存在したため、テキストボックスにファイル名とファイルのIDが表示されます。
検索条件を変更します。検索部分のコードを下記に変更します。検索文字列を "folder" に変更します。
IDriveSearchCollectionPage items = await client.Me.Drive.Search("folder").Request().GetAsync();
プロジェクトを実行し、[button1]をクリックします。folder を含むファイル、フォルダを検索します。"folder1" と "folder2" が
検索結果に該当し、2つの項目がテキストボックスに表示されます。
OneDriveのファイルやフォルダを検索できました。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2021-06-08
作成日: 2021-06-07