.NET MAUI Android平台如何检查图片文件是否存在?
在MAUI的Android平台检查打包图片是否存在
问题背景
通过项目文件中的MauiImage节点将图片添加到MAUI项目:
<MauiImage Include="Resources\Images\stickers\myimage0.png"/>
运行时通过平台差异代码加载图片:
#if IOS Source = ImageSource.FromFile($"{imageName}{imageNumber}.png"), #else Source = ImageSource.FromFile($"Resources/Images/stickers/{imageName}{imageNumber}.png"), #endif
iOS平台可通过FileSystem.AppPackageFileExistsAsync检查文件存在性:
#if IOS if (!await FileSystem.AppPackageFileExistsAsync($"{imageName}{imageNumber}.png")) continue; #endif
但Android平台无论是用FileSystem.AppPackageFileExistsAsync还是File.Exists都无法正确检测图片是否存在,需要找到Android平台的可行方案。
解决方案(Android平台)
Android平台中,通过MauiImage打包的图片会被放入APK的assets目录下,并非设备文件系统中的独立文件,因此无法通过常规文件系统API检测。需通过Android的AssetManager来验证资源是否存在:
#if ANDROID using Android.Content.Res; // 获取Android应用的AssetManager AssetManager assetManager = Android.App.Application.Context.Assets; try { // 尝试打开目标图片的资源流 using Stream stream = assetManager.Open($"Resources/Images/stickers/{imageName}{imageNumber}.png"); // 能成功打开流,说明图片存在,继续后续逻辑 } catch (FileNotFoundException) { // 打开失败,说明图片不存在,跳过当前项 continue; } #endif
原理说明
- MAUI在Android打包时,
Resources/Images下的资源会被映射到APK的assets/Resources/Images路径下 AssetManager是Android提供的专门用于访问APK内部资源的API,通过尝试打开资源流的方式可以判断资源是否存在- 若资源不存在,
assetManager.Open会抛出FileNotFoundException,捕获该异常即可判定文件不存在
内容的提问来源于stack exchange,提问作者Charles
相关产品推荐
相关产品推荐

