因为要使用C#操作Access数据库,安装程序的电脑上面安装的Access数据库版本不能确定,程序需要判断Access版本以便使用正确的连接处理程序。对于office的检测,一般会采用获取注册表的信息来判断当前安装软件的版本。本文整理了如何使用C#判断Access版本,具体代码如下:
public static void CheckVersion() { bool isInstalled = false; int version = 0; RegistryKey rk = Registry.LocalMachine; //office 97 RegistryKey v97 = rk.OpenSubKey(@"SOFTWARE\Microsoft\Office\8.0\Access\InstallRoot\"); //office 2000 RegistryKey v2000 = rk.OpenSubKey(@"SOFTWARE\Microsoft\Office\9.0\Access\InstallRoot\"); //office xp RegistryKey vxp = rk.OpenSubKey(@"SOFTWARE\Microsoft\Office\10.0\Access\InstallRoot\"); //office 2003 RegistryKey v2003 = rk.OpenSubKey(@"SOFTWARE\Microsoft\Office\11.0\Access\InstallRoot\"); //查询2007 RegistryKey v2007 = rk.OpenSubKey(@"SOFTWARE\Microsoft\Office\12.0\Access\InstallRoot\"); //查询2010 RegistryKey v2010 = rk.OpenSubKey(@"SOFTWARE\Microsoft\Office\14.0\Access\InstallRoot\"); //查询2013 RegistryKey v2013 = rk.OpenSubKey(@"SOFTWARE\Microsoft\Office\15.0\Access\InstallRoot\"); //查询2016 RegistryKey v2016 = rk.OpenSubKey(@"SOFTWARE\Microsoft\Office\16.0\Access\InstallRoot\"); if (v97 != null) { string file97 = vxp.GetValue("Path").ToString(); if (File.Exists(file97 + "MSACCESS.EXE")) { isInstalled = true; version = 97; } } if (v2000 != null) { string file2000 = vxp.GetValue("Path").ToString(); if (File.Exists(file2000 + "MSACCESS.EXE")) { isInstalled = true; version = 2000; } } if (vxp != null) { string filexp = vxp.GetValue("Path").ToString(); if (File.Exists(filexp + "MSACCESS.EXE")) { isInstalled = true; version = 2001; } } //检查本机是否安装Office2010 if (v2010 != null) { string file03 = v2010.GetValue("Path").ToString(); if (File.Exists(file03 + "MSACCESS.EXE")) { isInstalled = true; version = 2010; } } //检查本机是否安装Office2007 if (v2007 != null) { string office07 = v2007.GetValue("Path").ToString(); if (File.Exists(office07 + "MSACCESS.EXE")) { isInstalled = true; version = 2007; } } //检查本机是否安装Office2010 if (v2010 != null) { string office10 = v2010.GetValue("Path").ToString(); if (File.Exists(office10 + "MSACCESS.EXE")) { isInstalled = true; version = 2010; } } //检查本机是否安装Office2013 if (v2013 != null) { string office13 = v2013.GetValue("Path").ToString(); if (File.Exists(office13 + "MSACCESS.EXE")) { isInstalled = true; version = 2013; } } //检查本机是否安装Office2016 if (v2016 != null) { string office16 = v2016.GetValue("Path").ToString(); if (File.Exists(office16 + "MSACCESS.EXE")) { isInstalled = true; version = 2016; } } Debug.WriteLine("installed:" + isInstalled.ToString()); Debug.WriteLine("access version:" + version.ToString()); }
本人电脑安装的2007版本,经过上面的代码验证成功。Debug的结果是:
installed:True access version:2007
其他版本的因为没有安装,故没有经过实际测试,不过验证的方法应该大同小异,在真实使用时根据实际情况修改代码即可。
另外,以上代码可以经过修改,同样可以判断excel,word等是否安装及安装的版本。