How do I get the installation path for a given instance of SQL Server (default and name instances)
If you have the connection string, you may select the Directory with SQL
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;
}
Output of the above code:
c:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL