microkarl
Well-known member
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:
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
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: