Process cannot access a file because it is being used by another process

Ratel

New member
Joined
Aug 16, 2011
Messages
2
Location
Melbourne Australia
Programming Experience
3-5
Hi,

I frequently encounter “Process cannot access a file because it is being used by another process” error when trying to perform a file function (eg delete) that requires the Access Database file to be closed.

I open the database file in exclusive user mode as follows:
Dim ltStr As String
ltStr = "Provider=Microsoft.Jet.OLEDB.4.0; "
ltStr &= " Data Source=" + gtPath + "\abc.mdb; "
ltStr &= " Mode = Share Deny Read |Share Deny Write; "
ltStr &= " Jet OLEDBDatabase Password= '" & gtPassWord & "'"
oCon = New OleDbConnection(ltStr)
oCon.Open()

I attempt to delete the file with the following code :
oCon.Close()
oCon.Dispose()
System.IO.File.Delete("abc.mdb")
This works only about 5% of the time – 95% crashing with the process error described above.

I can dramatically improve the success rate to about 70% using the following code to try and close / dispose the connection multiple times
Do
TryAgain:
Try
System.IO.File.Delete("abc.mdb")
Catch ex As Exception
oCon.Close()
oCon.Dispose()
liCount = liCount + 1
If liCount > 10 Then
li = MsgBox("Can not Delete Files as they are still being used" & Chr(10) & "Do you wish to try again", MsgBoxStyle.YesNo, "Deletion Failed")
If li = 6 Then
GoTo TryAgain
Else
Exit Sub
End If
End Try
Application.DoEvents()
Loop

Is there anyway I can force the immediate closure of the connection so as to ensure the deletion works 100% of the time?

I am only opening the connection once at the start of the program.
Is this wrong – should I be opening / closing the connection at the start and end of each database query and update

Thanks
 
Back
Top