ADO.NET code for listing all available SQL Server databases


This code snippet will show you how to list all available databases on a SQL Server box. The trick here is to query master..sysdatabases



string sConn = "Server=(local);Database=master;Trusted_Connection=False;uid=sa;pwd=whatever;";
System.Data.SqlClient.SqlConnection oConn = 
	new System.Data.SqlClient.SqlConnection(sConn);

oConn.Open();

System.Data.SqlClient.SqlCommand oCommand = oConn.CreateCommand();
oCommand.CommandText = "select * from master..sysdatabases";
System.Data.SqlClient.SqlDataReader oReader = oCommand.ExecuteReader();

while (oReader.Read())
{
	string sName = oReader[0].ToString();
//add code to whatever you want with the name
}

oReader.Close();
oConn.Close();