There are alot of ways to accomplish this. The simplest one is to use the sp_databases procedure. Here's some example that uses this stored procedure in conjunction with ADO.NET to consume the returned data.
The sp_databases procedure lists databases that either reside in an instance of the SQL Server 2000/2005 Database Engine or are accessible through a database gateway. You can read this article from MSDN for more information about the sp_databases procedure.
//######################################//C# EXAMPLE//######################################//using SqlAdapter and DataTableusing (SqlDataAdapter adapter = new SqlDataAdapter("sp_databases", connectionString)){ adapter.SelectCommand.CommandType = CommandType.StoredProcedure; DataTable dataTable = new DataTable(); adapter.Fill(dataTable); foreach (DataRow dataRow in dataTable.Rows) { Console.WriteLine(dataRow["DATABASE_NAME"]); }}//using SqlCommand and SqlReaderusing (SqlCommand sqlCommand = new SqlCommand("sp_databases", new SqlConnection(connectionString))){ sqlCommand.CommandType = CommandType.StoredProcedure; sqlCommand.Connection.Open(); SqlDataReader sqlReader = sqlCommand.ExecuteReader(); while (sqlReader.Read()) { Console.WriteLine(sqlReader["DATABASE_NAME"]); } sqlReader.Close(); sqlCommand.Connection.Close();}
'######################################'VB.NET EXAMPLE'######################################'using SqlAdapter and DataTableUsing adapter As SqlDataAdapter = New SqlDataAdapter("sp_databases", connectionString) adapter.SelectCommand.CommandType = CommandType.StoredProcedure Dim table As New DataTable() adapter.Fill(table) For Each dr As DataRow In table.Rows Console.WriteLine(dr("DATABASE_NAME")) NextEnd Using'using SqlAdapter and DataTableUsing sqlCommand As SqlCommand = New SqlCommand("sp_databases", New SqlConnection(connectionString))) sqlCommand.CommandType = CommandType.StoredProcedure sqlCommand.Connection.Open() Dim sqlReader As SqlDataReader = sqlCommand.ExecuteReader() While (sqlReader.Read()) Console.WriteLine(sqlReader("DATABASE_NAME")) End While sqlReader.Close() sqlCommand.Connection.Close()End Using
*btw, you can also do this by using SMO or DMO. Read this article for more info.
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.