The process cannot access the file because it is being used by another process...

microkarl

Well-known member
Joined
Apr 22, 2004
Messages
82
Location
Morristown, NJ
Hi all,
I have a XMLDocument Class that tries to access a bunch of XML files in a folder. However, some of these XML files are still being written while its has been load. Of course, if I try to load them, I will get an Exception. such as "The process caanot access the file because it is being used by another process...". So I put a block of code before I actually load the files. See below:

Code:
  Dim doc As New XmlDocument()

   *** Wait for exclusive access to file ***
  Dim haveExclusiveAccess As Boolean = False
  Dim sr As StreamReader
  While haveExclusiveAccess = False
  	Try
           sr = New StreamReader(fileName)
           haveExclusiveAccess = True
           sr.Close()
        Catch
           haveExclusiveAccess = False
        End Try
  End While

  *** Access file ***
 doc.Load(fileName)
 ...

The above code should prevent me from getting the "Process Cannot access..." error, because if the file is being locked by another process, an exception will be thrown inside the catch block as soon as sr = New StreamReader(fileName) is executed. And it should be keep throwing and catching the exception until the file has been released from other program. In other words, the Access File block should not be executed as long as the targeted file is NOT released. I tried it for a couple dozen times, but for some crazy reasons, the streamreader block will not catch the exception and it will go through the doc.Load(fileName) block. Although it is a very rare case to me (literally 3 - 4 times out of 300 times), Is there anyway to absolutely gurantee the file that I am accessing is not locked at all?


Thanks in advance,
Carl
 
Last edited by a moderator:
Oh. By the way, the above problem seems to be happened on Windows 2003 Server. I tried nearly 200 times on Windows XP but it seems to be okay. Why is that???
 
Is there a possibility that a given XML file can be opened a 2nd (or 3rd) time by the external process? If so your code introduces a race condition i.e.

Code:
:retry_loop
check file

if not free goto retry_loop

//external program could reopen file here!

open file

you might be better just trying the doc.Load(...) within the try section and keep looping till it works.

Also exceptions are quite expensive in terms of performance as is doing a busy loop like your code - you might want to drop a delay of a couple of seconds after a failure before retrying.
 
Back
Top