I am developing a C# application with its backend as sqlite. In my application I have a button for cleaning the database (deleting the .db file and creating it again with some initial data). Sometimes when I try to delete the db it says it cannot be deleted because it is being used by another process. Before deleting it I am using close connection, dispose and clear pool functions. Even then it throws the same exception. Here is my code:
string targetDataBaseFilePath = Path.Combine(dataDirectoryPath, "local.db");
ThingzDatabase.Create(targetDataBaseFilePath, "touchdb");
In the create function I define the following code, from where I get the error:
if (File.Exists(DatabaseFileName))
{
try
{
ThingzDatabase.localdb.conn.Close();
ThingzDatabase.localdb.conn.Dispose();
SQLiteConnection.ClearAllPools();
}
catch (Exception)
{
}
File.Delete(DatabaseFileName); //error throws from here.
}
How can I prevent the error from being thrown?
You can delete the files yourself, but if any process accessing the database has crashed, or some process still has the database open, you may lose changes.
In Object Explorer, connect to an instance of the SQL Server Database Engine and then expand that instance. Expand Databases, right-click the database from which to delete the file, and then click Properties. Select the Files page. In the Database files grid, select the file to delete and then click Remove.
It's pretty straight forward - Open the connection, close the connection, delete the file. Avoid journal modes WAL and TRUNCATE for this (else you might have lingering journal files still) Make sure you do not have a second connection or connection pool which is not closed at the time of trying to delete the file.
FileInfo fi = new FileInfo(DatabasePath);
try
{
if (fi.Exists)
{
SQLiteConnection connection = new SQLiteConnection("Data Source=" + DatabasePath + ";");
connection.Close();
GC.Collect();
GC.WaitForPendingFinalizers();
fi.Delete();
}
}
catch(Exception ex)
{
fi.Delete();
}
DatabasePath is your database file path
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With