FolderPicker可讓您從檔案系統中挑選資料夾。
所需的 FolderPicker下列先決條件:
將權限新增至 AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
語法
C#
FolderPicker可以在 C# 中使用,如下所示:
async Task PickFolder(CancellationToken cancellationToken)
{
var result = await FolderPicker.Default.PickAsync(cancellationToken);
if (result.IsSuccessful)
{
await Toast.Make($"The folder was picked: Name - {result.Folder.Name}, Path - {result.Folder.Path}", ToastDuration.Long).Show(cancellationToken);
}
else
{
await Toast.Make($"The folder was not picked with error: {result.Exception.Message}").Show(cancellationToken);
}
}
Folder
記錄 Folder 代表檔案系統中的資料夾。 它會定義下列屬性:
- 路徑包含資料夾路徑。
- 名稱包含資料夾名稱。
FolderPickerResult
儲存 來自 PickAsync的資訊。
屬性
| 屬性 | 類型 | 描述 |
|---|---|---|
| Folder | Folder |
Folder取得 ,表示檔系統中選取的資料夾。 |
| 例外狀況 | Exception |
Exception如果挑選工作失敗,則取得 。 |
| IsSuccessful | bool |
取得值,判斷作業是否成功。 |
方法
| 方法 | 描述 |
|---|---|
| EnsureSuccess | 驗證挑選作業是否成功。 |
警告
EnsureSuccess 如果挑選工作失敗,會擲回 Exception 。
方法
| 方法 | 描述 |
|---|---|
| PickAsync | 要求許可權並允許在檔案系統中選取資料夾。 |
相依性註冊
如果您想要插入服務,您必須先註冊它。
使用下一個變更進行更新 MauiProgram.cs :
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.UseMauiCommunityToolkit();
// Register the FolderPicker as a singleton
builder.Services.AddSingleton<IFolderPicker>(FolderPicker.Default);
// Register the MainPage as transient to make sure it can resolve the IFolderPicker dependency.
builder.Services.AddTransient<MainPage>();
return builder.Build();
}
}
現在您可以插入服務,如下所示:
public partial class MainPage : ContentPage
{
private readonly IFolderPicker folderPicker;
public MainPage(IFolderPicker folderPicker)
{
InitializeComponent();
this.folderPicker = folderPicker;
}
async Task PickFolder(CancellationToken cancellationToken)
{
var result = await folderPicker.PickAsync(cancellationToken);
result.EnsureSuccess();
await Toast.Make($"Folder picked: Name - {result.Folder.Name}, Path - {result.Folder.Path}", ToastDuration.Long).Show(cancellationToken);
}
}
如需如何提供 CancellationTokenMicrosoft 檔的詳細資訊。
範例
您可以在 .NET MAUI Community Toolkit 範例應用程式中找到作用中的範例FolderPicker。
API
您可以在 .NET MAUI Community Toolkit GitHub 存放庫上找到 的FolderPicker原始程式碼。