嵌入资源文件可在Windows应用访问但在Xamarin上无法正常调用
核心原因
WPF/WinForm等Windows桌面项目的Properties.Resources强类型资源是.NET Framework针对Windows平台的专属特性,Xamarin.Forms作为跨平台框架没有内置这套实现,因此无法直接复用Windows端的代码,但可以通过标准嵌入资源方案实现同等便捷的访问效果。
实现步骤
1. 配置文件生成操作
- 打开你的Xamarin.Forms共享项目/类库项目,找到
Resources/template.xlsx文件,右键选择「属性」 - 将「生成操作」的值修改为**嵌入的资源(Embedded Resource)**并保存
2. 嵌入资源读取实现
你可以直接复用下面的通用读取代码,封装后可以实现和Windows端完全一致的强类型访问体验:
using System.IO; using System.Reflection; using Xamarin.Essentials; public static class AppResources { // 替换为你项目的默认命名空间,可在项目属性的「应用」 tab 中查看 private const string DefaultNamespace = "你的项目默认命名空间"; // 强类型访问Excel模板,用法和Windows端的Properties.Resources.template完全一致 public static byte[] Template => GetEmbeddedResourceBytes("Resources.template.xlsx"); private static byte[] GetEmbeddedResourceBytes(string resourceRelativePath) { var fullResourceName = $"{DefaultNamespace}.{resourceRelativePath}"; var assembly = Assembly.GetExecutingAssembly(); using var stream = assembly.GetManifestResourceStream(fullResourceName); if (stream == null) throw new FileNotFoundException("嵌入资源不存在", fullResourceName); var buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); return buffer; } }
3. 保存文件到磁盘
调用逻辑和Windows端基本一致,注意跨平台存储路径需要用Xamarin.Essentials提供的系统安全路径:
// 生成平台允许的应用私有存储路径 var savePath = Path.Combine(FileSystem.AppDataDirectory, "test.xlsx"); // 直接读取强类型资源保存 File.WriteAllBytes(savePath, AppResources.Template);
调试提示
如果运行时提示资源找不到,可以在代码中加入以下代码输出所有已嵌入的资源名称,核对你要的资源的准确拼写:
var allResources = Assembly.GetExecutingAssembly().GetManifestResourceNames(); foreach (var name in allResources) { System.Diagnostics.Debug.WriteLine(name); }
内容的提问来源于stack exchange,提问作者Stefan
相关产品推荐
相关产品推荐

