Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete sqlite db file

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?

like image 245
Sangeetha Avatar asked Jun 17 '11 10:06

Sangeetha


People also ask

Can I delete SQLite file?

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.

How do I delete a db file?

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.

Can I delete db journal file?

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.


1 Answers

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

like image 192
Akshay Mishra Avatar answered Oct 05 '22 00:10

Akshay Mishra