动态加载DLL

最近给客户的一个winform发布更新程序,但是因为当初固定了程序集列表,所以新加入的dll不会被客户下载,这就有个问题,新的application必须有那个dll才能运行,否则肯定报错。还好确定了一下,如果代码没有运行到某个dll的对象,那个dll是不会被AppDomain加载的,这样,只要在main入口,把dll文件生成就可以保证后面的程序运行正常了。

首先,把dll文件作为签入的资源文件,一起编译成exe,然后在main函数里面,把资源文件生成本地dll

基本代码是这样:

        static void Main(string[] args)
        {
            if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "SharpCompress.dll") == false)
            {
                Assembly assembly = typeof(Program).Assembly;
                //读取资源文件
                System.IO.Stream streamSmall = assembly.GetManifestResourceStream("AppUpdate.SharpCompress.dll");
                byte[] content = new byte[streamSmall.Length];
                streamSmall.Read(content,0,content.Length);
                //生成dll
                File.WriteAllBytes(AppDomain.CurrentDomain.BaseDirectory + "SharpCompress.dll", content);
            }
        }

 

posted @ 2016-09-04 09:33  IWing  阅读(345)  评论(0编辑  收藏  举报