.NET 8 MAUI项目Mac端读取JSON文件遇授权错误求助
解决.NET 8 MAUI在Mac上读取文件的权限问题
核心原因
Mac系统的沙箱机制会隔离MAUI应用的运行环境,Directory.GetCurrentDirectory()在Mac上返回的是应用沙箱内的路径,而非你的项目源代码目录。直接访问项目目录下的文件会被沙箱拦截,导致权限拒绝。Windows无沙箱限制所以能正常运行。
解决方案
方案1:使用嵌入式资源(推荐,跨平台最可靠)
将JSON本地化文件设置为嵌入式资源,直接从程序集读取,完全规避文件系统权限问题:
修改项目文件(.csproj),添加嵌入式资源配置:
<ItemGroup> <!-- 匹配所有Localization目录下的JSON文件 --> <EmbeddedResource Include="Resources\Localization\*.json"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </EmbeddedResource> </ItemGroup>修改读取代码,从程序集加载嵌入式资源:
// 替换成你项目中的实际类名(比如包含此代码的页面/服务类) var assembly = typeof(YourPageOrService).GetTypeInfo().Assembly; // 命名空间要和项目一致,格式:[项目命名空间].[目录结构].[文件名] string resourcePath = $"YourProjectNamespace.Resources.Localization.{languageCode}.json"; using (Stream stream = assembly.GetManifestResourceStream(resourcePath)) { if (stream == null) { throw new FileNotFoundException($"未找到本地化资源:{resourcePath}"); } using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { jsonContent = await reader.ReadToEndAsync(); } }
方案2:使用应用沙箱内的路径(适用于需要修改文件的场景)
如果需要读写可修改的本地化文件,需将文件放到MAUI允许访问的沙箱目录中:
获取应用的本地数据目录:
// 沙箱内的安全目录,Mac和Windows都支持 string localAppData = FileSystem.AppDataDirectory; string targetFolder = Path.Combine(localAppData, "Localization"); string filePath = Path.Combine(targetFolder, $"{languageCode}.json");首次启动时复制资源文件到沙箱目录:
// 确保目标目录存在 Directory.CreateDirectory(targetFolder); // 先从嵌入式资源读取文件内容(参考方案1的代码),再写入沙箱路径 if (!File.Exists(filePath)) { var assembly = typeof(YourPageOrService).GetTypeInfo().Assembly; string resourcePath = $"YourProjectNamespace.Resources.Localization.{languageCode}.json"; using (Stream sourceStream = assembly.GetManifestResourceStream(resourcePath)) using (FileStream targetStream = File.Create(filePath)) { await sourceStream.CopyToAsync(targetStream); } } // 之后就可以正常读写filePath了 using (StreamReader reader = new StreamReader(filePath, Encoding.UTF8)) { jsonContent = await reader.ReadToEndAsync(); }
额外排查步骤
- 用终端运行项目:尝试在项目目录下执行
dotnet maui run,排除VS Code调试器的权限问题。 - 确认Entitlements.plist:如果是用户手动选择文件的场景,需添加
com.apple.security.files.user-selected.read-only权限,但自带资源不需要此配置。
内容的提问来源于stack exchange,提问作者Lucas Wallner
相关产品推荐
相关产品推荐

