将C#的DLL文件合并成.EXE文件

4

我知道这个话题有很多回复,但是我在其中找到的示例代码并不适用于每个.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时却不能工作。这个“大”dll的设置与我的小程序相同。
我无法想象为什么它有时可以工作,有时又不能工作。我也试过用ICSharp.AvalonEdit.dll测试,但没有成功。
有人能想象错误在哪里吗?
编辑1:
当我启动我的程序时,它说找不到我的dll。
编辑2:
我想我已经找到了我的问题的核心。如果我要合并的dll之一包含对其他dll的引用,那么我就会遇到FileNotFound异常。有人知道如何加载/添加内部所需的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个回答

1
如果您的引用程序集需要其他程序集,则必须将它们与应用程序一起包含 - 要么在应用程序文件夹中,要么作为嵌入式资源。您可以使用Visual Studio、IL Spy、dotPeek确定引用的程序集,或者使用方法Assembly.GetReferencedAssemblies编写自己的工具。
还有可能在附加ResolveAssembly处理程序之前触发AssemblyResolve事件。在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 顶部的守卫条件,以避免排除任何引用的程序集。

使用您的代码后,我遇到了一些问题。请在这里展示。 - Karl_Schuhmann

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接