我正在开发一个 C# 应用程序,其后端为 sqlite。在我的应用程序中,我有一个用于清理数据库的按钮(删除 .db 文件并使用一些初始数据再次创建它)。有时,当我尝试删除数据库时,它说无法删除它,因为它正在被另一个进程使用。在删除它之前,我使用了关闭连接、处理和清除池功能。即使那样,它也会抛出相同的异常。这是我的代码:
string targetDataBaseFilePath = Path.Combine(dataDirectoryPath, "local.db");
ThingzDatabase.Create(targetDataBaseFilePath, "touchdb");
在创建函数中,我定义了以下代码,从那里我得到错误:
if (File.Exists(DatabaseFileName))
{
try
{
ThingzDatabase.localdb.conn.Close();
ThingzDatabase.localdb.conn.Dispose();
SQLiteConnection.ClearAllPools();
}
catch (Exception)
{
}
File.Delete(DatabaseFileName); //error throws from here.
}
如何防止错误被抛出?
最佳答案
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();
}
数据库路径 是你的数据库文件路径
关于sqlite - 删除sqlite db文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6384207/