将C#DLL合并到.EXE中

时间:2013-08-02 10:20:03

标签: c# wpf dll merge fluent

我知道有很多回复此主题,但我在此回复中找到的示例代码不适用于每个.dll

我使用this示例。

public App()
    {
        AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(ResolveAssembly);
    }

    static Assembly ResolveAssembly(object sender, ResolveEventArgs args)
    {
        //We dont' care about System Assemblies and so on...
        if (!args.Name.ToLower().StartsWith("wpfcontrol")) return null;

        Assembly thisAssembly = Assembly.GetExecutingAssembly();

        //Get the Name of the AssemblyFile
        var name = args.Name.Substring(0, args.Name.IndexOf(',')) + ".dll";

        //Load form Embedded Resources - This Function is not called if the Assembly is in the Application Folder
        var resources = thisAssembly.GetManifestResourceNames().Where(s => s.EndsWith(name));
        if (resources.Count() > 0)
        {
            var resourceName = resources.First();
            using (Stream stream = thisAssembly.GetManifestResourceStream(resourceName))
            {
                if (stream == null) return null;
                var block = new byte[stream.Length];
                stream.Read(block, 0, block.Length);
                return Assembly.Load(block);
            }
        }
        return null;
    }

当我创建一个只有一个窗口和一个按钮的小程序时它有效,但是我的“大”dll它没有用。 “big”dll上的设置与我的小程序中的设置相同。

我无法想象为什么它有时会起作用,有时它不起作用。我用ICSharp.AvalonEdit.dll测试了它,但是没有成功..

谁能想象出错误在哪里?

编辑1

当我开始我的程序时,它说它无法找到我的dll。

编辑2

我认为我得到了我的问题的核心。如果我要合并的其中一个dll包含对其他dll的引用,那么我将成为此FileNotFoundException异常。有人知道如何加载/添加内部所需的dll的

编辑3

当我使用JiříPolášek的代码时,它适用于某些人。我的Fluent显示错误“请,请附上带样式的ResourceDictionary。但我已经在App.xaml

中完成了此操作
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://application:,,,/Fluent;Component/Themes/Office2010/Silver.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources> 

1 个答案:

答案 0 :(得分:1)

如果引用的程序集需要其他程序集,则必须将它们与应用程序一起包含在应用程序文件夹或嵌入式资源中。您可以使用Visual Studio,IL Spy,dotPeek确定引用的程序集,或使用方法Assembly.GetReferencedAssemblies编写自己的工具。

在将AssemblyResolve处理程序附加到它之前,也可能触发ResolveAssembly事件。附加处理程序应该是您在Main方法中执行的第一件事。在WPF中,您必须使用新的Main方法创建新类,并在项目设置中将其设置为 Startup object

public class Program
{
    [STAThreadAttribute]
    public static void Main()
    {
        AppDomain.CurrentDomain.AssemblyResolve
            += new ResolveEventHandler(ResolveAssembly);
        WpfApplication1.App app = new WpfApplication1.App();
        app.InitializeComponent();
        app.Run();
    }

    public static Assembly ResolveAssembly(object sender, ResolveEventArgs args)
    {   
      // check condition on the top of your original implementation
    }
}

您还应检查ResolveAssembly顶部的防护条件,以排除任何引用的程序集。

相关问题