How to list available instances of SQL Servers using SMO in C#?

Cute picture Cute · Jul 15, 2009 · Viewed 17.9k times · Source

Can anybody explain me what I wrong I am doing in the following piece of code:

DataTable dt=SmoApplication.EnumAvailableSqlServer(true);
Server sr = new Server("Test");

foreach(DataBase db in sr.DataBases)
{
    Console.WriteLine(db["name"]);
}

It gives an exception in sr.Databases that can not be connected.

Answer

Kredns picture Kredns · Jul 15, 2009

Take a look at the following links they may be helpful:

Alternatively you could change your code to this:

DataTable dt = SmoApplication.EnumAvailableSqlServers(false);
if (dt.Rows.Count > 0)
{
    foreach (DataRow dr in dt.Rows)
    {
        Console.WriteLine(dr["Name"]);
    }
}

Hope this solves your problem.