c#解决dll调用的问题

 在做一个c#中间程序时,调用第三方的dll安装路径“Program Files” 和“Program Files (x86)”的问题,经过一段时间的研究,找到了下面的解决方案:

思路:

  1.配置dll的加载路径

  2.监控dll

  3.dll加载失败判断操作系统位数(x86、x64)

  4.动态加载dll

 

解决方案:

1.在config中添加dll引用配置:

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="{dll name}" publicKeyToken="{ dll token}" culture="neutral"/>
        <codeBase version="{版本}" href="{dll file path}"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>

2.在程序入口处注册dll引用失败的事件

static void Main(string[] args)
{
    System.AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
}

private static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
}

3.实现引用失败的dll的重新加载

private static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            System.Reflection.AssemblyName name = new System.Reflection.AssemblyName(args.Name);
            if (name.Name == "{you dll name}")
            {
                if (Win32Native.Is64BitOperatingSystem)
                {
                    if (System.IO.File.Exists(@"{your dll file path}"))
                    {
                        return System.Reflection.Assembly.LoadFile(@"your dll file path");
                    }
                }
                else
                {
                    if (System.IO.File.Exists(@"your dll file path"))
                    {
                        return System.Reflection.Assembly.LoadFile(@"your dll file path");
                    }
                }
            }
            return null;
        }

注意:Is64BitOperatingSystem是用来判断操作系统的位数. .net4.0及以上有直接判断方法可以调用,需要通用的方法可以参考 http://www.cnblogs.com/zp900704/p/7553939.html

posted @ 2017-09-20 11:18  zhao379028604  阅读(1550)  评论(0编辑  收藏  举报