Question

I'm have a web application, that creates an Access database. When I'm creating this database, I first have to delete the file if it exists and then recreate it.

            if (File.Exists(DataSourcePath + fileName))
                File.Delete(DataSourcePath + fileName);

            string cnnStr = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + DataSourcePath + fileName + "; Jet OLEDB:Engine Type=5";
            var catType = Type.GetTypeFromProgID("ADOX.Catalog");
            object o = Activator.CreateInstance(catType);
            catType.InvokeMember("Create", BindingFlags.InvokeMethod, null, o, new object[] { cnnStr });

            OleDbConnection cnn = new OleDbConnection(cnnStr);
            var cmd = cnn.CreateCommand();

            cnn.Open();
            cmd.CommandText = "CREATE TABLE TblInfoCompany (Name TEXT, Family TEXT)";
            cmd.ExecuteNonQuery();

            cmd.Dispose();
            cnn.Close();
            cnn.Dispose();

When I'm recreating this file, I can get an exception. Exception says: "The file is used in another process." Please help me to close this process or to find any way to solve this problem.

Thanks.

Was it helpful?

Solution

The process mantaining the file in use is probably the web application itself. Since closing/opening that mdf file is not directly handled by you, but from the Jet Engine, it is not so easy. I would suggest to PInvoke the system function MoveFileEx specifying:

  • null as a second parameter meaning you want to delete
  • MOVEFILE_DELAY_UNTIL_REBOOT as dwFlags, meaning the operation would be done at next system restart

I know is not the best since server are not so frequently shut down, but is probably the simpler solution to delete a locked file you can't close elseway.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top