Example #1
0
        private string GetExpressInstance()
        {
            string ExpressInstance = "";

            try
            {
                String[] InstanceNames;
                ExpressInstance = @"Server=localhost";  //.\SQLEXPRESS

                // *******************************************************************************************
                // * WORKS IN both x86 x64 mode
                // *******************************************************************************************
                RegistryKey localMachine = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);
                RegistryKey windowsNTKey = localMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server");
                InstanceNames = (String[])windowsNTKey.GetValue("InstalledInstances");


                if (InstanceNames.Length == 1)
                {
                    ExpressInstance = @"Server=.\" + InstanceNames[0];
                }
                else if (InstanceNames.Length > 0)
                {
                    foreach (String InstanceName in InstanceNames)
                    {
                        if (InstanceName.Contains("EXPRESS"))
                        {
                            ExpressInstance = @"Server=.\" + InstanceName;
                        }
                        //Console.Write(element);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Unable able to find SQL Server 2008 r2 Express Instance", ex);
            }

            return(ExpressInstance);
        }