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

使用Costura.Fody时如何将程序集内嵌文件复制到指定目录

解决Costura.Fody打包嵌入式文件后的提取问题

核心原因

用Costura.Fody打包后,你的电子表格文件是作为嵌入式资源嵌入到EXE中的,并非存放在程序集所在目录的物理文件,所以通过Assembly.GetExecutingAssembly().Location拼接路径自然找不到文件。

正确的提取步骤

1. 确认文件的嵌入式资源名称

在项目中右键电子表格文件→属性→生成操作选择「嵌入式资源」。资源名称通常为「项目命名空间.文件夹层级.文件名」,比如项目命名空间是MyApp,文件放在Resources文件夹下,文件名为Data.xlsx,资源名就是MyApp.Resources.Data.xlsx。

2. 从程序集读取资源流并写入目标文件

使用以下代码提取文件:

using System.IO;
using System.Reflection;

public void ExtractEmbeddedFile(string resourceName, string targetPath)
{
    Assembly assembly = Assembly.GetExecutingAssembly();
    
    using (Stream resourceStream = assembly.GetManifestResourceStream(resourceName))
    {
        if (resourceStream == null)
        {
            throw new FileNotFoundException("找不到指定的嵌入式资源", resourceName);
        }
        
        using (FileStream fileStream = new FileStream(targetPath, FileMode.Create, FileAccess.Write))
        {
            resourceStream.CopyTo(fileStream);
        }
    }
}

3. 调用示例

假设要将文件复制到用户指定的C:\User\Target\Data.xlsx:

string resourceName = "MyApp.Resources.Data.xlsx"; // 替换为你的实际资源名
string targetPath = @"C:\User\Target\Data.xlsx";
// 确保目标文件夹存在
Directory.CreateDirectory(Path.GetDirectoryName(targetPath));
ExtractEmbeddedFile(resourceName, targetPath);

排查技巧

  • 可通过以下代码获取所有嵌入式资源名称,确认你使用的资源名是否正确:
foreach (string name in Assembly.GetExecutingAssembly().GetManifestResourceNames())
{
    Console.WriteLine(name);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 09:03:19