You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Avalonia开发MacOS应用:如何引用App Bundle中的文件?

解决MacOS App Bundle中文件读取问题

方法1:读取物理文件(复制到输出目录)

当你将文件设置为复制到输出目录时,文件会随程序集一起打包到App Bundle的Contents/MacOS目录下。此时可以通过程序集的路径来定位文件:

  1. 在项目文件(.csproj)中配置文件的复制属性:
<ItemGroup>
  <None Update="Repository\CreateTables.sql">
    <CopyToOutputDirectory>Always</CopyToOutputDirectory>
  </None>
</ItemGroup>
  1. 使用程序集路径拼接目标文件路径:
using System.IO;
using System.Reflection;

// 获取当前程序集所在目录
var assemblyDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
// 拼接目标文件路径
var sqlFilePath = Path.Combine(assemblyDir, "Repository", "CreateTables.sql");
// 读取文件内容
string assets = File.ReadAllText(sqlFilePath);

方法2:嵌入资源读取(无需物理文件)

将文件嵌入到程序集中,通过Avalonia的资源加载器读取,无需处理路径问题:

  1. 在项目文件中配置文件为嵌入资源:
<ItemGroup>
  <EmbeddedResource Update="Repository\CreateTables.sql" />
</ItemGroup>
  1. 使用Avalonia的AssetLoader读取资源:
using Avalonia.Platform;
using System.IO;

// 替换为你的程序集名称(csproj中的AssemblyName)
var resourceUri = new Uri("avares://YourAssemblyName/Repository/CreateTables.sql");
using var stream = AssetLoader.Open(resourceUri);
using var reader = new StreamReader(stream);
string assets = reader.ReadToEnd();

关键说明

  • Environment.GetCurrentDirectory()在MacOS运行时返回的是用户的工作目录(而非App Bundle内部路径),因此不能用来定位Bundle内的文件。
  • 若你的文件放在App Bundle的Contents/Resources目录下,可通过程序集路径向上导航到Contents目录后再拼接Resources路径:
var contentsDir = Directory.GetParent(assemblyDir).Parent.FullName;
var sqlFilePath = Path.Combine(contentsDir, "Resources", "Repository", "CreateTables.sql");

内容的提问来源于stack exchange,提问作者RLU

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 03:45:34