英文:
Dotnet Maui Blazor App - How to access images in wwwroot from static classin android platform?
问题
在Maui Blazor Android平台应用程序中,我需要访问wwwroot文件夹或存储图像文件的某个位置作为文件。
在Windows上:
string rootpath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot");
和
var logoPath = "/img/proxiwash_black.jpg";
运行良好。
当我切换到Android时,它会出现指定文件未找到的错误。
请帮忙。谢谢...
英文:
In Maui Blazor Android Platform App I need to access wwwroot folder or somewhere image files are stored as file.
On Windows :
string rootpath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot");
and
var logoPath = "/img/proxiwash_black.jpg";
works well.
When I switch to Android it gives error like specified file not found.
Please help. Thanks...
答案1
得分: 0
对于 Android 平台,静态文件将被打包到 APK 文件中,不会存储在用户可见的任何文件夹中,因此会引发文件未找到的错误。
此外,该文件只能在 Android 上读取。您可以使用 .NET MAUI 文件系统助手 来访问它,例如 FileSystem.OpenAppPackageFileAsync("wwwroot/data.txt")
;
有关更多信息,您可以参考关于 .NET MAUI 中静态资产仅限于 Razor 组件的官方文档。
英文:
For the android platform, the static file will be packaged into the apk file. It will not be stored in any folder which user can see. So it will throw error about file not found.
In addition, the file can only read on the android. And you can use the .net maui file system helpers to access it. Scuh as FileSystem.OpenAppPackageFileAsync("wwwroot/data.txt")
;
For more information, you can refer to the official document about the Static assets limited to Razor components in the .net maui.
答案2
得分: 0
After getting help with Liyun, I added more and converted stream to byte[] with example:
public static class ResourceLoader {
public async static Task<byte[]> LoadMauiAsset(string fileName)
{
using var stream = await FileSystem.OpenAppPackageFileAsync(fileName);
return await StreamToByteArrayAsync(stream);
}
public static async Task<byte[]> StreamToByteArrayAsync(Stream stream)
{
using MemoryStream memoryStream = new MemoryStream();
await stream.CopyToAsync(memoryStream);
return memoryStream.ToArray();
}
}
I hope this helps everyone.
ps. Do not forget to place your images in "Resources\Raw" in dotnet maui project.
英文:
After getting help with Liyun, I added more and converted stream to byte[] with example:
public static class ResourceLoader {
public async static Task<byte[]> LoadMauiAsset(string fileName)
{
using var stream = await FileSystem.OpenAppPackageFileAsync(fileName);
return await StreamToByteArrayAsync(stream);
}
public static async Task<byte[]> StreamToByteArrayAsync(Stream stream)
{
using MemoryStream memoryStream = new MemoryStream();
await stream.CopyToAsync(memoryStream);
return memoryStream.ToArray();
}
}
I hope this helps everyone.
ps. Do not forget to place your images in "Resources\Raw" in dotnet maui project.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论