我正在制作一个应用程序,它是一个用户界面,用于访问两种类型的数据库——SQLite 和 SQL Server。
问题是,SQLite 不需要“安装”,因为它只是一个平面文件数据库,但另一方面,SQL Server(Express/普通)需要在使用前安装。我的问题很简单:
Is there a way by which i can find out if an instance of SQL Server has been installed on the local machine by using a C# program?
最佳答案
您有几种方法可以做到这一点:
- SmoApplication.EnumAvailableSqlServers()
- SqlDataSourceEnumerator.Instance
- 直接访问系统注册表
直接访问不是 MS 推荐的解决方案,因为它们可以更改 key /路径。但其他解决方案并不健壮,无法在 64 位平台上提供实例。
因此我更喜欢在系统注册表中检查 SQL Server 实例。为此,请记住 x86 和 x64 平台在注册表访问方面的差异。 Windows 64 位将数据存储在系统注册表的不同部分并将它们组合到 View 中。所以使用 RegistryView 是必不可少的。
using Microsoft.Win32;
RegistryView registryView = Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32;
using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView))
{
RegistryKey instanceKey = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL", false);
if (instanceKey != null)
{
foreach (var instanceName in instanceKey.GetValueNames())
{
Console.WriteLine(Environment.MachineName + @"\" + instanceName);
}
}
}
如果您要在 64 位操作系统上寻找 32 位实例(很奇怪,但可能),您需要查看:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server
关于c# - 通过C#检查机器上是否安装了SQL Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2443001/