且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用C#获取本地SQL Server实例

更新时间:2023-02-08 14:13:18

EnumAvailableSqlServers SqlDataSourceEnumerator 只会在SQL Server浏览器中找到命名实例服务正在运行。



Manag edComputer 只能找到在SQL Server Management Studio中注册的服务器。



如果你只是在当前计算机上寻找服务器,你可以从注册表中读取信息。密钥 HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft / Microsoft Microsoft SQL Server 具有名为 InstalledInstances 的值,其中包含本地计算机上安装的SQL Server实例:

EnumAvailableSqlServers and SqlDataSourceEnumerator will only find named instances if the SQL Server Browser services is running.

ManagedComputer will only find servers registered in SQL Server Management Studio.

If you're just looking for servers on the current computer, you can read the information from the registry. The key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server has a value called InstalledInstances which contains the name of the SQL Server instances installed on the local computer:
public static class SqlHelper
{
    public static IEnumerable<string> ListLocalSqlInstances()
    {
        if (Environment.Is64BitOperatingSystem)
        {
            using (var hive = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
            {
                foreach (string item in ListLocalSqlInstances(hive))
                {
                    yield return item;
                }
            }
            
            using (var hive = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
            {
                foreach (string item in ListLocalSqlInstances(hive))
                {
                    yield return item;
                }
            }
        }
        else
        {
            foreach (string item in ListLocalSqlInstances(Registry.LocalMachine))
            {
                yield return item;
            }
        }
    }
    
    private static IEnumerable<string> ListLocalSqlInstances(RegistryKey hive)
    {
        const string keyName = @"Software\Microsoft\Microsoft SQL Server";
        const string valueName = "InstalledInstances";
        const string defaultName = "MSSQLSERVER";
        
        using (var key = hive.OpenSubKey(keyName, false))
        {
            if (key == null) return Enumerable.Empty<string>();
            
            var value = key.GetValue(valueName) as string[];
            if (value == null) return Enumerable.Empty<string>();
            
            for (int index = 0; index < value.Length; index++)
            {
                if (string.Equals(value[index], defaultName, StringComparison.OrdinalIgnoreCase))
                {
                    value[index] = ".";
                }
                else
                {
                    value[index] = @".\" + value[index];
                }
            }
            
            return value;
        }
    }
}