Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"file in use by another process" error while trying to delete a database file

Tags:

c#

winforms

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?

like image 201
Gali Avatar asked Nov 13 '22 18:11

Gali


1 Answers

You could try and force garbage collection by running

GC.Collect();

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.

Conn.Dispose();
//Nothing says GC will run exactly now
File.Delete(@"C:\Some-file-used-by-Conn.db");

Your options are to force garbage collection or to delay the deletion in some way.

like image 167
Jesper Palm Avatar answered Dec 22 '22 09:12

Jesper Palm