How do I allow a file to be released before trying to access it?

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Im calling an external MFC program to decrypt a text file before I open it. But im getting the standard "file in use" error. My code is:
<pre class="prettyprint lang-vb Private Sub decrypt(ByVal fin As String, ByVal fout As String, ByVal mode As Char, Optional ByVal ReplaceSourceFile As Boolean = False)
Dim psi As New ProcessStartInfo
psi.FileName = "decrypt.exe"
psi.Arguments = """" & fin & """ """ & fout & """ mypassword "
psi.CreateNoWindow = True
psi.UseShellExecute = False
With New Process
.StartInfo = psi
.Start()
If Not .WaitForExit(1000) Then .Kill()
While .HasExited = False
System.Threading.Thread.Sleep(250)
End While
.Dispose()
End With
psi = Nothing
If ReplaceSourceFile Then
Do
Try
Debug.WriteLine("deleting")
File.Delete(fin)
Catch ex As Exception
Debug.WriteLine(ex.Message)
System.Threading.Thread.Sleep(1000)
End Try
Loop
Debug.WriteLine("moving")
File.Move(fout, fin)
End If
End Sub[/code]
Once it hits the loop trying to delete fin, I see in my immediate window the following three lines repeated over and over until I click the stop button in VS:
deleting<br/>
A first chance exception of type System.IO.IOException occurred in mscorlib.dll<br/>
The process cannot access the file myfile.txt because it is being used by another process.
So the file never seems to unlock after the MFC app exits, no matter how large the Sleep interval is. I can sleep it for a full minute and it will still throw the exception. However, if I put a MessageBox in the loop, it seems to allow the file to unlock
because after I dismiss the MessageBox, itll delete the file and exit the loop.
Has anyone ran into this behavior and is there a way to write this code to make it work?
Thanks!

View the full article
 
Back
Top