FolderPicker
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
记录表示文件系统中的文件夹。 它定义以下属性:
- 路径包含文件夹路径。
- 名称包含文件夹名称。
FolderPickerResult
存储来自 PickAsync
的信息。
属性
属性 | 类型 | 描述 |
---|---|---|
Folder | Folder |
获取表示文件系统中所选文件夹的 Folder 。 |
Exception | 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);
}
}
有关如何提供 CancellationToken
的更多详细信息,请参阅 Microsoft 文档。
示例
可以在 .NET MAUI 社区工具包示例应用程序中查找 FolderPicker
的示例。
API
可以在 .NET MAUI 社区工具包 GitHub 存储库查看FolderPicker
的源代码