如何获取指定 SQL Server 实例(包括默认实例和命名实例)的安装路径?
如何获取指定 SQL Server 实例(包括默认实例和命名实例)的安装路径?
using(RegistryKey sqlServerKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server"))
{
foreach (string subKeyName in sqlServerKey.GetSubKeyNames())
{
if(subKeyName.StartsWith("MSSQL."))
{
using(RegistryKey instanceKey = sqlServerKey.OpenSubKey(subKeyName))
{
string instanceName = instanceKey.GetValue("").ToString();
if (instanceName == "MSSQLSERVER")//say
{
string path = instanceKey.OpenSubKey(@"Setup").GetValue("SQLBinRoot").ToString();
path = Path.Combine(path, "sqlserver.exe");
return path;
}
}
}
}
}
private string ServerRootDirectory(string connString)
{
string path = string.Empty;
using (SqlConnection con = new SqlConnection(connString))
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = string.Format(@"DECLARE @InstanceName varchar(100),
@InstanceLocation varchar(100),
@InstancePath varchar(100)
SELECT @InstanceName = convert(varchar, ServerProperty('InstanceName'))
EXEC master..xp_regread @rootkey='HKEY_LOCAL_MACHINE',
@key='Software\Microsoft\Microsoft SQL Server\Instance Names\SQL',
@value_name=@InstanceName,
@value=@InstanceLocation OUTPUT
SELECT @InstanceLocation = 'Software\Microsoft\Microsoft SQL Server\'+@InstanceLocation+'\Setup'
EXEC master..xp_regread @rootkey='HKEY_LOCAL_MACHINE',
@key=@InstanceLocation,
@value_name='SQLPath',
@value=@InstancePath OUTPUT
SELECT @InstancePath as RootDirectoryPath");
path = (string)cmd.ExecuteScalar();
con.Close();
}
return path;
}
c:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL