Search code examples
fileexceptionprocessvbscriptlocked

How can I get rid of wait time between 2 methods that access the same file?


I have the following piece of VBSCript code to find a section (strSection) and an item in that section (strItem) in a plain text file.

Do While Not myINIFile.AtEndOfStream
  sl_Sleep(100)
  s = myINIFile.ReadLine <--- **This is the line that rises the exception**
  If s = strSection Then
    'Find the correct line
    Do While Not myINIFile.AtEndOfStream
      s = myINIFile.ReadLine
      If InStr(s, strItem)>0 Then
        Exit Do
      End if              
    Loop            
    Exit Do
  End if              
Loop 

It seems that if I do not put the Sleep(100) (milliseconds) (or use lower values like 20 or 50) I eventually get an exception that says "The process cannot access the file because another process has locked a portion of the file".

I think that the condition in the Do While is the ReadLine method is being called while the AtEndOfStream has not yet finished. However, using 100 msecs for every line is slowing down the process to unacceptable speeds.

Is this what is really happening or is the problem somewhere else? Is there anything that I can do to prevent this process from being locked or to wait a little more (until it is freed) only if it is locked so it does not raise an exception?


EDIT: This code loops through a file that looks like this:

[Section1]    
param1 = 100    
param2 = 200    
param3 = 300    

[Section2]    
param1 = 1000    
param2 = 2000    
param3 = 3000

[Section3]    
param1 = 1
param2 = 2
param3 = 5
param4 = 10
param5 = 20

The code is supposed to go through the file until it finds the [SectionX] line (strSection) and then keep reading lines until it finds the "paramx" line (strItem). This line is then kept stored in 's' and it is processed later on.


Solution

  • the code you posted works perfectly for me. i don't get an exception...

    are you accessing the file anywhere else while using your posted code?

    have you tried reading the entire file and then parse the string? see http://www.motobit.com/tips/detpg_asp-vbs-read-write-ini-files/