I have a PC.sdf file that I work with. I close the connection and I need to delete it.
I open the connection like this:
bool OpenConn()
{
try
{
Conn = new SqlCeConnection(String.Format(@"Data Source={0}\{1}", PathI, "PC.SDF"));
Conn.Open();
return true;
}
catch
{
//MessageBox.Show(err.Message, "Connetion error");
return false;
}
}
I close it like this:
Conn.Close();
Conn.Dispose();
I try to delete it like this:
if (File.Exists(@"\myPath\PC.sdf"))
File.Delete(@"\myPath\PC.sdf");
But I get this error: file in use by another process. What could be the cause of this error, and how can I fix it?
You could try and force garbage collection by running
Do this after you have Closed and Disposed of the DB object.
This will of course only work if that is the only reference to that database file.
Edit: Answer to comment about that you shouldn’t use GC.Collect to “fix” other issues.
I don’t think this is because of another issue. The garbage collector runs at an indeterminate time chosen by the runtime. This means that you can’t rely on your object being disposed of between the followings lines.
Your options are to force garbage collection or to delay the deletion in some way.