I have an MDF file that I\'m attaching to my local SQL server during testing with MSTEST and I don\'t want to have to go delete those temporary databases by hand after I\'ve
feO2x's answer works great but he didn't give code. The following works if you have your database connection string in your app.config.
using System.Configuration;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Common;
public class Foo
{
public static void DropDatabase(string connectionName)
{
using (
var sqlConnection =
new SqlConnection(
ConfigurationManager.ConnectionStrings[connectionName]
.ConnectionString))
{
var serverConnection = new ServerConnection(sqlConnection);
var server = new Microsoft.SqlServer.Management.Smo.Server(
serverConnection);
server.KillDatabase(sqlConnection.Database);
}
}
}
You must reference System.Data, *System.Configuratio*n, Microsoft.SqlServer.ConnectionInfo, Microsoft.SqlServer.Management.Sdk.Sfc, and Microsoft.SqlServer.Management.Smo.