如何在 .NET MAUI 中打包和读取资源文件

本教程介绍了在 .NET MAUI 应用中打包(MauiAsset)和读取(OpenAppPackageFileAsync)应用内资源文件的标准方法,并附带了文件拷贝的代码示例。

  1. 把需要打包的文件放到Resources\Raw\目录下。

  2. 设置文件的生成操作Build Action为MauiAsset

  3. 使用using (Stream instream = FileSystem.Current.OpenAppPackageFileAsync(fileName))读取文件。

  4. 将文件拷贝到其他目录

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    // Open the source file
        using Stream inputStream = await FileSystem.Current.OpenAppPackageFileAsync(filename);
    
        // Create an output filename
        string targetFile = Path.Combine(FileSystem.Current.AppDataDirectory, filename);
    
        // Copy the file to the AppDataDirectory
        using FileStream outputStream = File.Create(targetFile);
        await inputStream.CopyToAsync(outputStream);
    
Built with Hugo
Theme Stack designed by Jimmy