开发者

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

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

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.


I would try it like this below. This puts your connection inside a using block which will call dispose the connection for you once it goes out of scope. This should allow you to delete the file immediately after as all of the file locks associated with it should be released.

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");


The two responses above are both good considerations for ensuring that it is not YOUR application which is the one using the database file.

I'm not exactly sure what an .SDF file is, but a quick google search suggests that it may be a MS SQL database file. If so, depending on your system and your operating conditions, you may want to consider using 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜