将DLL嵌入EXE

First, add the dll to Reference and set Copy Local to False.

enter image description here

Then create a new project folder "libs", copy the referenced dll into this folder, and set Build Action to "Embedded Resources"

enter image description here

In the main() method, add code to handle the exception "dll not found".

    static void Main()
    {
        AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
    private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs e)
    {
        //embeddll是项目的命名空间, dll资源在libs文件夹下,所以这里用的命名空间为: embeddll.libs.
        string _resName = "embeddll.libs." + new AssemblyName(e.Name).Name + ".dll";
        using (var _stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(_resName))
        {
            byte[] _data = new byte[_stream.Length];
            _stream.Read(_data, 0, _data.Length);
            return Assembly.Load(_data);
        }
    }

猜你喜欢

转载自www.cnblogs.com/jizhiqiliao/p/13207660.html
今日推荐