Reputation: 11
I m generating a database file dynamically to a specific location on a button click. And I delete the database dynamically by using File.Delete() function which deletes the .MDF and .LDF file from that location. But when I m trying to create the database again with the same name... It throws an error of "Database already exists. Choose a different name". Is there any other way of completely deleting that database file from the file system?
Upvotes: 1
Views: 995
Reputation: 56
Have you looked at this SO question: Deleting database from C#
There are examples on how to delete the database from SQL server through C#.
Upvotes: 1
Reputation: 23797
Instead of using File.Delete(), ask SQL Server to drop the database. During drop operation it deletes the related files. ie:
using (var con = new SqlConnection(@"server=.\SQLExpress;Trusted_Connection=yes"))
{
con.Open();
new SqlCommand("drop database myDbName", con).ExecuteNonQuery();
con.Close();
}
Upvotes: 2