Maui 文件系统帮助程序

[删除(380066935@qq.com或微信通知)]

更好的阅读体验请查看原文:https://learn.microsoft.com/zh-cn/dotnet/maui/platform-integration/storage/file-system-helpers?tabs=android&view=net-maui-7.0

本文介绍如何使用 .NET 多平台应用 UI (.NET MAUI) IFileSystem 接口。 此接口提供访问应用的缓存和数据目录的帮助程序方法,并帮助访问应用包中的文件。

接口的默认实现 IFileSystem 可通过 FileSystem.Current 属性使用。 IFileSystem接口和FileSystem类都包含在命名空间中Microsoft.Maui.Storage

使用文件系统帮助程序

每个操作系统都有应用缓存和应用数据目录的唯一路径。 该 IFileSystem 接口提供用于访问这些目录路径的跨平台 API。

缓存目录

获取应用程序的目录以存储缓存数据。 缓存数据可用于需要保留的时间超过临时数据的任何数据,但不应是运行应用所需的数据,因为操作系统可能会清除此存储。

string cacheDir = FileSystem.Current.CacheDirectory;

应用数据目录

若要获取应用顶级目录,任何不是用户数据文件的文件。 这些文件是使用同步框架的操作系统进行备份的。

string mainDir = FileSystem.Current.AppDataDirectory;

捆绑文件

若要打开捆绑到应用包中的文件,请使用 OpenAppPackageFileAsync 该方法并传递文件名。 此方法返回一个只读 Stream 表示文件内容。 以下示例演示如何使用方法读取文件的文本内容:

public async Task<string> ReadTextFile(string filePath)
{
    using Stream fileStream = await FileSystem.Current.OpenAppPackageFileAsync(filePath);
    using StreamReader reader = new StreamReader(fileStream);

    return await reader.ReadToEndAsync();
}

从捆绑文件写入应用数据文件夹

无法修改应用的捆绑文件。 但可以先读取它,然后将其写回 缓存目录应用数据目录。 以下示例用于 OpenAppPackageFileAsync 读取捆绑文件、更改该文件,然后将其写入应用数据文件夹:

public async Task ConvertFileToUpperCase(string sourceFile, string targetFileName)
{
    // Read the source file
    using Stream fileStream = await FileSystem.Current.OpenAppPackageFileAsync(sourceFile);
    using StreamReader reader = new StreamReader(fileStream);

    string content = await reader.ReadToEndAsync();

    // Transform file content to upper case text
    content = content.ToUpperInvariant();

    // Write the file content to the app data directory
    string targetFile = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, targetFileName);

    using FileStream outputStream = System.IO.File.OpenWrite(targetFile);
    using StreamWriter streamWriter = new StreamWriter(outputStream);

    await streamWriter.WriteAsync(content);
}

平台差异

本部分介绍特定于平台的文件系统帮助程序的差异。

  • Android FileSystem.CacheDirectory
    返回当前上下文的 CacheDir

  • IOS\macOS FileSystem.AppDataDirectory
    返回当前上下文的 FilesDir ,从 API 23 及更高版本开始使用 自动备份进行备份

  • Windows FileSystem.OpenAppPackageFileAsync
    可以使用此方法打开添加到具有 MauiAsset生成操作的项目的文件。 .NET MAUI 项目将处理 Resources\Raw 文件夹中的任何文件作为 MauiAsset