Error "file in use by another process" when trying to delete a database file

I have a file PC.sdfI'm working with. I close the connection and I need to remove it.

I open the connection as follows:

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 am trying to remove 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 causing this error and how can I fix it?

+5
source share
3 answers

You can try to force garbage collection by running

GC.Collect();

Do this after closing and deleting the DB object.

This, of course, will only work if it is the only link to this database file.

: , GC.Collect "" .

, - . , . , , .

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

- - .

+1

. , , . , , , .

bool OpenConn()
{
  try
  {
     using(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;
   }
}

if (File.Exists(@"\myPath\PC.sdf"))
    File.Delete(@"\myPath\PC.sdf");
0

, , .

I'm not quite sure what a .SDF file is, but a quick Google search suggests that it could be an MS SQL database file. If so, depending on your system and operating conditions, you might want to use the ALTER DATABASE SET SINGLE_USER command:

ALTER DATABASE [YourDbName]
SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

http://blog.sqlauthority.com/2010/02/11/sql-server-alter-database-dbname-set-single_user-with-rollback-immediate/

0
source

All Articles