user3501832
user3501832

Reputation: 11

How to delete a dynamically generated database file (.MDF and .LDF) from the filesystem and from SQL server using c#

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

Answers (2)

Fraser Molyneux
Fraser Molyneux

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

Cetin Basoz
Cetin Basoz

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

Related Questions