Hello,
I am writing a VBString, what is the fastest way to open
a file and search a string and read a few characters
after that string?
Thanks,
Jim.

Re: find a string in a file by Al

Al
Mon Aug 25 21:05:23 CDT 2003


"Richard Mueller [MVP]" <rlmueller@ameritech.net> wrote in message
news:O7OI9N3aDHA.2548@TK2MSFTNGP09.phx.gbl...
> Jim wrote:
>
> > Hello,
> > I am writing a VBString, what is the fastest way to open
> > a file and search a string and read a few characters
> > after that string?
>
> Hi,
>
> The FileSystemObject can open a file for read access. The ReadAll method
> will read the entire file into a variable.

It turns out that the .ReadAll method is slow on larger files, apparently
because, internally, it reads to a buffer and concatenates the results into
your variable. The time it takes to do a .ReadAll increases more than
linearly with file size. If you are reading a LARGE file, determine the size
of the file (with the .Size property of the FILE object), and then .Read
that many bytes.

> Then, you can use the InStr
> function to find the first occurrance of a search string. Then, you can
use
> the Mid function to extract a few characters after. A quick example that
> displays the 7 characters in the file that follow the first occurrance of
> the string "name=":
>
> Option Explicit
>
> Dim objFSO, objFile, strFile, intIndex, strContents, strFound
>
> strFile = "c:\rlm\HilltopLab\NewScripts\ParseTest.txt"
> Set objFSO = CreateObject("Scripting.FileSystemObject")
> Set objFile = objFSO.OpenTextFile(strFile, 1)
> strContents = objFile.ReadAll
> intIndex = InStr(1, strContents, "name=", vbTextCompare)
> If intIndex = 0 Then
> Wscript.Echo "Search string not found"
> Else
> strFound = Mid(strContents, intIndex + 5, 7)
> Wscript.Echo strFound
> End If
>
> Note that intIndex + 5 is used in the Mid function, because intIndex
> indicates the position in the file where the string "name=" starts. If the
> string is not found, intIndex will be 0.

Another method that avoids the index calculation is to parse using the SPLIT
function, i.e. replace the code following the .ReadAll above with:

splitter = split( strContents, "name=", -1, vbTextCompare )
if ( ubound( splitter ) < 1 ) then
Wscript.Echo "Search string not found"
Else
strFound = left( splitter(1), 7 )
Wscript.Echo strFound
End If


If you are willing to accept a nill return result as equivalent to string
not found, this can be simplified to:

splitter = split( strContents & "name=", "name=", -1, vbTextCompare )
strFound = left( splitter(1), 7 )

/Al