1

I was creating connection string for sql express database dynamically.I wanted to know how to get the name of the server instance running currently in the local machine,programatically using c#.

1 Answer 1

2

You can use the following code:

using System;
using Microsoft.Win32;

namespace TestConsoleApp
{
    class Program
    {
      static void Main()
      {
        RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server");
        String[] instances = (String[])rk.GetValue("InstalledInstances");
        if (instances.Length > 0)
        {
           foreach (String element in instances)
           {
              if (element == "MSSQLSERVER")
                 Console.WriteLine(System.Environment.MachineName);
              else
                 Console.WriteLine(System.Environment.MachineName + @"\" + element);
           }
        }
        Console.ReadKey();
      }
    }
}

Edit:

If you wish to get the instances that are in running state, please refer to this link: http://support.microsoft.com/kb/q287737/

Sign up to request clarification or add additional context in comments.

3 Comments

but how will i know the currently running instance?
Do you mean, the one whose service is on running state?
ya true, the one on which service is on running state

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.