使用OleDb关闭与Access DB的连接

tra*_*ber 2 c# oledb ms-access

我有一个Access数据库,我正在与OleDb连接.连接和使用一切正常,但我需要备份文件.

我正在关闭连接:

  public class myDbHandlerClass
  {

    private OleDbConnection myConnection;
    //in reality this string gets built by properties to the class
    //it ends up being this...
    //Yes Jet 4.0 this is an Access 2003 database
    private string myConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=myDatabase.mdb";

    public void OpenDatabase()
    {
      //to open the database
      try
      {
        // Does a previous connection exist?
        if ((myConnection != null) && myConnection.State != ConnectionState.Closed) return;

        //No database connection string is specified, can't continue
        if (string.IsNullOrEmpty(myConnectionString)) return;

        myConnection = new OleDbConnection(myConnectionString);
        myConnection.Open();

      }
      catch (Exception ex)
      {
        ExTrace.WriteLineIf(TraceLog.TraceError, ExTrace.ShowException(ex));
      }
    }

    public void CloseDatabase()
    {
      try
      {
        if ((myConnection == null)) return;

        if (myConnection.State != ConnectionState.Closed) myConnection.Dispose();
        myConnection = null;
        GC.Collect();
      }
      catch (Exception ex)
      {
        ExTrace.WriteLineIf(TraceLog.TraceError, ExTrace.ShowException(ex));
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

没有抛出异常,连接状态==关闭,myConnection == null,但.ldb文件永远不会消失.我的后续代码应该将"myDatabase.mdb"文件移动到"myDatabase.bak"失败,因为该文件已被我的程序使用.

如何确保它实际上已关闭且未锁定.

编辑:我修改了代码与以下评论的建议,现在它正在工作.

myConnection.Dispose(); 
Run Code Online (Sandbox Code Playgroud)

并明确调用GC.Collect()

是它的工作原理.

谢谢您的帮助!

Yur*_*ter 5

myConnection.Close();试试之后myConnection.Dispose();

作为事实上,我beleive .Dispose()被关闭连接一样,所以简单的更换.Close().Dispose()应该做的伎俩.