通过C#检查计算机上是否安装了SQL Server

Shr*_*yas 9 c# sql-server sqlite

我正在创建一个应用程序,它是一个用户界面,可以访问两种类型的数据库 - SQLite和SQL Server.

问题是,SQLite不需要"安装",因为它只是一个flatfile数据库,但另一方面,SQL Server(Express/normal)需要在使用前安装.我的问题很简单:

有没有办法可以通过使用C#程序找出本地计算机上是否已安装SQL Server实例?

Ale*_*aus 17

你有几种方法可以做到:

  • SmoApplication.EnumAvailableSqlServers()
  • SqlDataSourceEnumerator.Instance
  • 直接访问系统注册表

直接访问不是MS推荐的解决方案,因为它们可以更改密钥/路径.但其他解决方案并不健全,无法在64位平台上提供实例.

因此,我更喜欢检查系统注册表中的SQL Server实例.这样做,请记住x86x64平台之间注册表访问的区别.Windows 64位将数据存储在系统注册表的不同部分,并将它们组合到视图中.所以使用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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您在64位操作系统上寻找32位实例(非常奇怪,但可能),您需要查看:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server
Run Code Online (Sandbox Code Playgroud)


小智 10

如果您的应用程序安装在相关计算机上,您可以使用类似于以下内容的方式检查注册表:

using Microsoft.Win32; 
RegistryKey RK = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\MICROSOFT\Microsoft SQL Server");
    if(RK != null)
    {
       // It's there 
    }
    else
    {
       // It's not there 
    }
Run Code Online (Sandbox Code Playgroud)