.NET MAUI实战 FilePicker

1.概要

最近在迁移 GeneralUpdate.Tool的时候需要用到文件选择,在MAUI中可以使用FilePicker进行选择。

ref1: https://gitee.com/Juster-zhu/GeneralUpdate

ref2:https://docs.microsoft.com/zh-cn/dotnet/maui/platform-integration/storage/file-picker?tabs=windows.

.NET MAUI实战 FilePicker

2.详细内容

提供的默认文件类型包括 FilePickerFileType.ImagesFilePickerFileType.PngFilePickerFilerType.Videos。 可以通过创建类的 FilePickerFileType 实例,为每个平台指定自定义文件类型。 此类的构造函数采用由类型键键标识平台的 DevicePlatform 字典。 字典键的值是表示文件类型的字符串集合。 例如,下面介绍如何指定特定的漫画文件类型:

var customFileType = new FilePickerFileType(
               new Dictionary<DevicePlatform, IEnumerable<string>>
              {
                  { DevicePlatform.iOS, new[] { "public.my.comic.extension" } }, // or general UTType values
                  { DevicePlatform.Android, new[] { "application/comics" } },
                  { DevicePlatform.WinUI, new[] { ".cbr", ".cbz" } },
                  { DevicePlatform.Tizen, new[] { "*/*" } },
                  { DevicePlatform.macOS, new[] { "cbr", "cbz" } }, // or general UTType values
              });

PickOptions options = new()
{
   PickerTitle = "Please select a comic file",
   FileTypes = customFileType,
};

该方法 PickAsync 提示用户从设备选取文件。 使用 PickOptions 类型指定选取器允许的标题和文件类型。 以下示例演示如何打开选取器并处理所选图像:

public async Task<FileResult> PickAndShow(PickOptions options)
{
   try
  {
       var result = await FilePicker.Default.PickAsync(options);
       if (result != null)
      {
           if (result.FileName.EndsWith("jpg", StringComparison.OrdinalIgnoreCase) ||
               result.FileName.EndsWith("png", StringComparison.OrdinalIgnoreCase))
          {
               using var stream = await result.OpenReadAsync();
               var image = ImageSource.FromStream(() => stream);
          }
      }
       return result;
  }
   catch (Exception ex)
  {
       // The user canceled or something went wrong
  }
   return null;
}

如果希望用户选取多个文件,请调用该方法 FilePicker.PickMultipleAsync 。 此方法还采用参数 PickOptions 来指定其他信息。 结果与返回的类型相同 PickAsync,但不 FileResult 返回类型, IEnumerable<FileResult> 而是使用所有选定文件返回类型。