Embedding DLLs in a compiled executable

前端 未结 16 2737
情深已故
情深已故 2020-11-21 07:07

Is it possible to embed a pre-existing DLL into a compiled C# executable (so that you only have one file to distribute)? If it is possible, how would one go about doing it?<

16条回答
  •  旧时难觅i
    2020-11-21 07:30

    Just right-click your project in Visual Studio, choose Project Properties -> Resources -> Add Resource -> Add Existing File… And include the code below to your App.xaml.cs or equivalent.

    public App()
    {
        AppDomain.CurrentDomain.AssemblyResolve +=new ResolveEventHandler(CurrentDomain_AssemblyResolve);
    }
    
    System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
    {
        string dllName = args.Name.Contains(',') ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll","");
    
        dllName = dllName.Replace(".", "_");
    
        if (dllName.EndsWith("_resources")) return null;
    
        System.Resources.ResourceManager rm = new System.Resources.ResourceManager(GetType().Namespace + ".Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());
    
        byte[] bytes = (byte[])rm.GetObject(dllName);
    
        return System.Reflection.Assembly.Load(bytes);
    }
    

    Here's my original blog post: http://codeblog.larsholm.net/2011/06/embed-dlls-easily-in-a-net-assembly/

提交回复
热议问题