Intermittent File Lock Bug With Streamwriter

D

Don

I have a strange bug popping up every once in a while. I've got a section
of code that executes these statements when working with a streamwriter:


--- Start ---

....

' Close the streamwriter
_fileWriter.Close()

' Move the file we just closed
IO.File.Move(currentPath, newPath)

....

--- End ---


That is, I am writing text (to a new file that I create) using a
streamwriter, closing the streamwriter, then moving the file. This works
about 95% of the time. When it doesn't work, I get the following error
(I've cut out the file path):


--- Start ---

The process cannot access the file "..." because it is being used by another
process.
Source : mscorlib
Reflected Type : System.IO.__Error, mscorlib, Version=1.0.5000.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089
Target Site : WinIOError

* Stack Trace *

Error at : System.IO.__Error.WinIOError(Int32 errorCode, String str)
Error at : System.IO.File.Move(String sourceFileName, String destFileName)
Error at : MyFunction()

--- End ---


It seems as thought the CLR is not releasing the file quickly enough when
the streamwriter.Close() method is called, and the IO.File.Move() method
craps out because of that. I've try forcing garbage collection (i.e.
GC.Collect() ), but that doesn't work. I've tried using timed loops to
repeatedly try to move the file until it works, but that doesn't succeed
either.

This code works fine almost all of the time. Only once in a while does it
fail. It's very difficult to reproduce the bug during normal operation, but
I can get it to occur about 5-10 times out of 100 if I repeatedly call the
method that executes this code in a test loop. In the cases where it does
fail, I can't figure out how to force VB.NET to let go of the file so I can
move it! Does anyone have any thoughts or suggestions?


- Don
 
G

Guest

Don't know what's cause of your issue.
It's OK even if I am doing:

Private Sub Test()
Dim i As Integer
For i = 0 To 100
Dim myFileStream As New FileStream("Test.txt", FileMode.CreateNew)
Dim myStream As New StreamWriter(myFileStream)
myStream.WriteLine("sdfasdfasdf")
myStream.Close()
File.Move("Test.txt", String.Format("test{0}.txt", i.ToString))
Next
MsgBox("OK")
End Sub
 
C

Chris

Have you tried flushing the stream before you close it? Not sure if
that will help, but it's worth a shot.
Are you using threading to accomplish anything?
 
D

Don

The streamwriter is set to Autoflush, actually, and I'm not using threading.
I realized that the issue is a little more complex than I at first thought.
There are issues of class constructors being fired only when one of their
members is first used. It's a bit complex, but it might have something to
do with it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top