C# How to get SQL Server installation path programatically?

后端 未结 3 2082
失恋的感觉
失恋的感觉 2020-12-06 19:38

How do I get the installation path for a given instance of SQL Server (default and name instances)

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-06 20:04

    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

提交回复
热议问题