MAUI程序Windows运行正常,Android提示文件不存在问题求助
MAUI程序Android平台读取Raw资产文件异常解决
问题场景
我编写了一个MAUI程序,功能是读取topics.txt文本文件内容并存入列表,Windows平台运行正常,但Android平台启动时抛出异常,调试确认是找不到文件导致的,且已确认该文件已添加为MAUI资产。
原代码示例
public partial class MainPage : ContentPage { static string filePath = @"Resources\Raw\topics.txt"; static List<string> topics = File.ReadAllLines(filePath).ToList(); Random random = new Random(); public MainPage() { InitializeComponent(); label.Text = "press the white button and start chatting"; } private void next_Clicked(object sender , EventArgs e) { int randomIndex = random.Next(topics.Count); if (topics.Count != 0) { label.Text = topics[randomIndex]; topics.RemoveAt(randomIndex); } else { label.Text = "Sorry.." + "\nwe ranout of topics"; } } }
Android平台异常信息
System.Reflection.TargetInvocationException Message=Exception has been thrown by the target of an invocation.
异常根源为Android平台无法找到指定路径的文件。
项目配置与文件结构
csproj关键配置
<PropertyGroup> <TargetFrameworks>net6.0-android;</TargetFrameworks> <TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('windows'))">$(TargetFrameworks);net6.0-windows10.0.19041.0</TargetFrameworks> <OutputType>Exe</OutputType> <RootNamespace>salfaty</RootNamespace> <UseMaui>true</UseMaui> <SingleProject>true</SingleProject> <ImplicitUsings>enable</ImplicitUsings> <!-- Display name --> <ApplicationTitle>Salfaty</ApplicationTitle> <!-- App Identifier --> <ApplicationId>com.companyname.salfaty</ApplicationId> <ApplicationIdGuid>537C4D54-BA75-4443-9A42-B77DE374E8FE</ApplicationIdGuid> <!-- Versions --> <ApplicationDisplayVersion>1.0</ApplicationDisplayVersion> <ApplicationVersion>1</ApplicationVersion> <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">21.0</SupportedOSPlatformVersion> <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">10.0.17763.0</SupportedOSPlatformVersion> <TargetPlatformMinVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">10.0.17763.0</TargetPlatformMinVersion> </PropertyGroup> <ItemGroup> <!-- App Icon --> <MauiIcon Include="Resources\AppIcon\appicon.svg" Color="#301934" /> <!-- Splash Screen --> <MauiSplashScreen Include="Resources\Splash\splash.svg" Color="#301934" BaseSize="128,128" /> <!-- Images --> <MauiImage Include="Resources\Images\*" /> <MauiImage Update="Resources\Images\dotnet_bot.svg" BaseSize="168,208" /> <!-- Custom Fonts --> <MauiFont Include="Resources\Fonts\*" /> <!-- Raw Assets (also remove the "Resources\Raw" prefix) --> <MauiAsset Include="Resources\Raw\**" LogicalName="%(RecursiveDir)%(Filename)%(Extension)" /> </ItemGroup>
文件结构
项目根目录下包含Resources文件夹,其下有AppIcon、Splash、Images、Fonts、Raw子文件夹,topics.txt文件位于Resources\Raw目录下。
问题原因与解决方案
问题根源
- Windows平台下,
Resources\Raw\topics.txt是本地文件系统的真实路径,因此File.ReadAllLines可以直接读取。 - Android平台中,MAUI的Raw资产会被打包到APK的
assets目录中,并非本地文件系统的独立文件,无法通过传统文件路径访问。 - 静态字段初始化时机过早,Android平台的应用环境尚未完全准备,此时尝试读取资产会失败。
修复代码
将文件读取逻辑改为MAUI跨平台资产读取API,并将读取操作移至页面构造函数中执行:
using System.IO; using System.Linq; using Microsoft.Maui.Storage; public partial class MainPage : ContentPage { List<string> topics = new List<string>(); Random random = new Random(); public MainPage() { InitializeComponent(); label.Text = "press the white button and start chatting"; // 异步加载主题文件,避免阻塞UI _ = LoadTopicsAsync(); } private async Task LoadTopicsAsync() { try { // 直接使用文件名,因为csproj配置已移除Resources\Raw前缀 using var stream = await FileSystem.OpenAppPackageFileAsync("topics.txt"); using var reader = new StreamReader(stream); string content = await reader.ReadToEndAsync(); // 按换行分割内容并移除空行 topics = content.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries).ToList(); } catch (Exception ex) { label.Text = $"加载主题失败: {ex.Message}"; } } private void next_Clicked(object sender , EventArgs e) { if (topics.Count != 0) { int randomIndex = random.Next(topics.Count); label.Text = topics[randomIndex]; topics.RemoveAt(randomIndex); } else { label.Text = "Sorry.." + "\nwe ranout of topics"; } } }
关键说明
- 使用
FileSystem.OpenAppPackageFileAsync方法:这是MAUI提供的跨平台API,可直接访问打包进应用的资产文件,无需关心不同平台的路径差异。 - 异步读取:避免同步操作阻塞UI线程,提升应用流畅性。
- 移除静态字段读取:将文件读取逻辑移至页面构造函数,确保Android平台环境已准备完成。
内容的提问来源于stack exchange,提问作者sakejha
相关产品推荐
相关产品推荐

