将C#DLL合并到.EXE中

卡尔·舒曼

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

我用了这个例子。

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的引用,则我将成为此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> 
吉里·波拉什克(JiříPolášek)

如果引用的程序集需要其他程序集,则还必须在应用程序中包括它们-在应用程序文件夹中或作为嵌入式资源。您可以使用Visual Studio,IL Spy,dotPeek确定引用的程序集,也可以使用method编写自己的工具Assembly.GetReferencedAssemblies

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

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以不排除任何引用的部件。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章