使用.NET MAUI中的文件
#dotnet #csharp #ios #maui

在本文中,我想谈论移动设备上的文件。我们将创建文件,在文件资源管理器中打开它们,然后按类型过滤。让我们走。

最重要的是,让我们创建一个简单的毛伊岛项目:

dotnet new maui -n FilePickAndSaveSample

让我们转到“mainpage.xamlâ文件并删除verticalstacklayout block中的所有元素。不需要我们。 > 下一步,您需要安装“ communityToolkit.maui套件。完成之后,应该注册它。为此,请访问“ mauiprogram.cs”并添加此代码:

var builder = MauiApp.CreateBuilder();
        builder
            .UseMauiApp<App>()
            .UseMauiCommunityToolkit()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
            });

接下来,让我们将保存文件保存到我们的移动设备。让我们回到我们的“mainpage.xamlâ文件,添加几个项目:按钮和标签。

<Label
    HorizontalOptions="Center"
    HorizontalTextAlignment="Center"
    LineBreakMode="WordWrap"
    Text="The FileSaver provides the ability to select target     folder and save files to the file system." />

<Button
    Clicked="SaveFile_Clicked"
    HorizontalOptions="Center"
    Text="Save file" />

然后转到“ mainpage.xaml.cs”文件,然后创建两个处理程序:

private async void SaveFile_Clicked(object sender, EventArgs e)
    {
        CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
        CancellationToken cancellationToken = cancellationTokenSource.Token;

        try
        {
            await SaveFile(cancellationToken);
        }
        catch (OperationCanceledException)
        {
            throw new OperationCanceledException("It was cancelled");
        }
    }

,也让我们创建一个单独的保存文件方法:

private async Task SaveFile(CancellationToken cancellationToken)
    {
        using var stream = new MemoryStream(Encoding.Default.GetBytes("Hello from the Dev.to Community!"));
        var fileName = Application.Current?.MainPage?.DisplayPromptAsync("FileSaver", "Choose filename") ?? Task.FromResult("untitled.txt");
        var fileSaverResult = await FileSaver.Default.SaveAsync(await fileName, stream, cancellationToken);
        if (fileSaverResult.IsSuccessful)
        {
            await Toast.Make($"The file was saved successfully to location: {fileSaverResult.FilePath}").Show(cancellationToken);
        }
        else
        {
            await Toast.Make($"The file was not saved successfully with error: {fileSaverResult.Exception.Message}").Show(cancellationToken);
        }
    }

但不是全部。让我们回到“ mauiprogram.cs”文件和注册服务,只需添加此行:

builder.Services.AddSingleton(FileSaver.Default);

顺便说一句。您可能如何注意到我们注入了Service FileSaver静态方式,但是您可以使用另外两种方式:注入构造函数或创建新实例。为了方便,我将使用静态注射。

,但是无论如何,让我们检查一下。

Stage 1: main

单击“保存txt”按钮:

Stage 1: type name

键入“plain_text.txtâ和点击OK。此外,选择本地存储并进入其中。重复相同的doc_text.docâ和“ pic.jpeg”的过程

现在,让我们为Pick文件夹创建服务。这是与保存文件相似的所有内容。首先,转到“ mauipragram.cs”文件并注册新服务:

builder.Services.AddSingleton(FolderPicker.Default);

,还添加lable和按钮:

<Label
    HorizontalOptions="Center"
    HorizontalTextAlignment="Center"
    LineBreakMode="WordWrap"
    Text="FolderPicker allows you to pick a folder from the  device" />

<Button
    Clicked="PickFolder_Clicked"
    HorizontalOptions="Center"
    Text="Pick Folder" />

还需要处理程序和方法:

private async void PickFolder_Clicked(object sender, EventArgs e)
    {
        CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
        CancellationToken cancellationToken = cancellationTokenSource.Token;

        try
        {
            await PickFolder(cancellationToken);
        }
        catch (OperationCanceledException)
        {
            throw new OperationCanceledException("It was cancelled");
        }
    }

    private async Task PickFolder(CancellationToken cancellationToken)
    {
        var folderResult = await FolderPicker.PickAsync("DCIM", cancellationToken);
        if (folderResult.IsSuccessful)
        {
            var filesCount = Directory.EnumerateFiles(folderResult.Folder.Path).Count();
            await Toast.Make($"Folder picked: Name - {folderResult.Folder.Name}, Path - {folderResult.Folder.Path}, Files count - {filesCount}", ToastDuration.Long).Show(cancellationToken);
        }
        else
        {
            await Toast.Make($"Folder is not picked, {folderResult.Exception.Message}").Show(cancellationToken);
        }
    }

让我们退房:

Stage 2: main

单击“选择文件夹”,然后选择文件夹。如果再次点击按钮,您将处于与之前选择的同一文件夹。

Stage 2: selected folder

和我想显示的最后一件事,是按类型进行选择的文件。让我们做并注册服务:

builder.Services.AddSingleton(FilePicker.Default);

添加lable和几个按钮:

<Label
    HorizontalOptions="Center"
    HorizontalTextAlignment="Center"
    LineBreakMode="WordWrap"
    Text="FilePicker allows you to pick a file from the device" />

<Button
    Clicked="PickPhoto_Clicked"
    HorizontalOptions="Center"
    Text="Pick a Photo" />

<Button
    Clicked="PickFile_Clicked"
    HorizontalOptions="Center"
    Text="Pick a File" />

<Label
    FontSize="15"
    HorizontalTextAlignment="Center"
    x:Name="FileName" />

添加处理程序:

private async void PickPhoto_Clicked(object sender, EventArgs e)
    {
        FileResult result = await _filePicker.PickAsync(new PickOptions
        {
            PickerTitle = "Pick a Photo",
            FileTypes = FilePickerFileType.Images
        });

        if (result == null) return;

        FileName.Text = result.FileName;
    }

    private async void PickFile_Clicked(object sender, EventArgs e)
    {
        var customFileTypes = new FilePickerFileType(new Dictionary<DevicePlatform, IEnumerable<string>>
        {
            {
                DevicePlatform.iOS, new[]
                {

                    "com.microsoft.word.doc",
                    "public.plain-text",
                    "org.openxmlformats.wordprocessingml.document"
                }
            },
            {
                DevicePlatform.Android, new[]
                {
                    "application/msword",
                    "text-plain",
                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                }
            },
            {
                DevicePlatform.WinUI, new[]
                {
                    "doc","docx", "txt"
                }
            },
        });

        FileResult result = await _filePicker.PickAsync(new PickOptions
        {
            PickerTitle = "Pick a File",
            FileTypes = customFileTypes
        });

        if (result == null) return;

        FileName.Text = result.FileName;
    }

现在我们可以退房。如果单击“选择照片”,则只能选择图片。

Stage 3: main

Stage 3: filtered file

就是全部。资料来源:CLICK

快乐编码!

Buy Me A Beer