Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to get SQL Server installation path programatically?

Tags:

c#

sql-server

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

like image 548
Julius A Avatar asked Jul 22 '09 14:07

Julius A


1 Answers

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;
                }
            }
        }
    }
}
like image 118
Julius A Avatar answered Sep 22 '22 03:09

Julius A