关于根据Build Platform或者OS 加载x86或者x64 dll的问题

      最近编程遇到引用SQLite.dll的问题。SQLite.dll有两个版本,x86和x64,如果仅仅是自己的环境使用,那么添加对应版本的引用,那是完全没有问题的。但是一旦程序要发布出去,或者在不用的平台环境上使用,那么这么做就存在隐患了。最终就需要根据不同系统环境来加载dll。

      首先,是判断系统平台。

      1. IntPtr

      在build platform是Any CPU的情况,根据IntPtr.Size的值判断是x86还是x64。

 1    if (IntPtr.Size == 8)
 2             {
 3                 //x64
 4             }
 5             else if (IntPtr.Size == 4)
 6             {
 7                 //x86
 8             }
 9             else
10             {
11                 //other
12             }

      如果build platform是x86或者x64,那么IntPtr.Size就跟OS 平台没有关系,得到的大小是build platform对应的值。

      

      2.WMI

      这个方法是用OS接口的扩展方法,判断OS平台,完全不会受到build platform的影响。需要添加对System.Management.dll的引用。 

 1 SelectQuery query = new SelectQuery("select AddressWidth from Win32_Processor");
 2             ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
 3             ManagementObjectCollection moCollection = searcher.Get();
 4             foreach (ManagementObject mo in moCollection)
 5             {
 6                 foreach (PropertyData property in mo.Properties)
 7                 {
 8                     if (property.Name.Equals("AddressWidth"))
 9                     {
10                         UInt16 i =  Convert.ToUInt16(property.Value);
11                     }
12                 }
13             } 

  

      3.Environment.Is64BitOperatingSystem

      如果你的程序的.Net Framework版本是4.0及以上的话,可以直接使用这个属性判断OS版本

      判断完OS版本之后,是加载dll.

      由于我的是WPF程序,使用AppDomain的事件方法加载。   

 1         public MainWindow()
 2         {
 3             AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => CurrentDomain_AssemblyResolve();
 4             InitializeComponent();           
 5         }
 6 
 7         private System.Reflection.Assembly CurrentDomain_AssemblyResolve()
 8         {
 9             Assembly loadedAssembly = null;
10             if (IntPtr.Size == 8)
11             {
12                 loadedAssembly = Assembly.LoadFile("***");
13             }
14             else if (IntPtr.Size == 4)
15             {
16                 loadedAssembly = Assembly.LoadFile("***");
17             }
18             else
19             {
20                 //
21             }
22             return loadedAssembly;
23         }

     

原文地址:https://www.cnblogs.com/ByronsHome/p/3771061.html