Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File.Delete error "The process cannot access the file because it is being used by another process"

I have written a DotUnit test suite for testing some data import functionality in my application. It works by making a backup of some local Microsoft Access Database, let's call it 'Test.mdb', to 'Test.mdb.bak', performing some data import (and subsequent Assert checks) and then restoring the original from the backup.

The SetUp() function creates a backup if one doesn't exist.

The TearDown() function attempts to delete 'Test.mdb' and then copy 'Test.mdb.bak' to 'Test.mdb'.

Intermittently running the tests fail with this error "The process cannot access the file because it is being used by another process".

I've had a look the MSDN on File.Delete and IO permissions but couldn't find what I was after. Does anyone know if there is a .NET feature that will allow me to completely lock the file before attempting to delete it? Or find which process is accessing it at the time of deletion?

like image 718
sonelliot Avatar asked Nov 23 '25 09:11

sonelliot


1 Answers

I had a similar issue while unit testing Entity Framework code using a SQLite database where each test needed to use a fresh instance of a database, so my the [TestCleanup] method was doing a File.Delete on the database, but was getting the same "used by another process" error.

Before I called, File.Delete, I had to add the following to fix my issue.

GC.Collect();

GC.WaitForPendingFinalizers();

[TestInitialize]
public void MyTestInitialize()
{
    // Copies the embedded resource 'MyDatabase.db' to the Testing Directory
    CommonTestFixture.UnpackFile("MyDatabase.db", this.GetType(), this.TestContext.TestDeploymentDir);
}

[TestCleanup]
public void MyTestCleanup()
{
    // Adding the following two lines of code fixed the issue
    GC.Collect();
    GC.WaitForPendingFinalizers();

    // Removes 'MyDatabase.db' from the testing directory.
    File.Delete(Path.Combine(this.TestContext.TestDeploymentDir, "MyDatabase.db"));
}

[TestMethod]
public void GetVenueTest()
{
    // CreateTestEntities() is a helper that initializes my entity framework DbContext
    // with the correct connection string for the testing database.
    using (var entityFrameworkContext = CreateTestEntities())
    {
        // Do whatever testing you want here:
        bool result = entityFrameworkContext.TestSomething()
        Assert.IsTrue(result);
    }
}
like image 97
Scott Avatar answered Nov 24 '25 22:11

Scott



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!