Reputation: 199
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#.
Upvotes: 1
Views: 2377
Reputation: 15571
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/
Upvotes: 2