Check whether a given string exists in a file

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi All,

Is there a command to check whether a given string is present in a text
file, without having to read the contents of the file, a line at a time and
then check for the given string?

Thanks.
kd
 
kd said:
Is there a command to check whether a given string is present in a text
file, without having to read the contents of the file, a line at a time
and
then check for the given string?

No. You can use 'ReadToEnd' to read the whole file into a string and use
'InStr' to check for the pattern, but this is only recommended for small
files.
 
kd said:
Is there a command to check whether a given string is present in a text
file, without having to read the contents of the file, a line at a time and
then check for the given string?

Well, you could do something like

Private Function FindInFile(ByVal searchPattern As String, ByVal path As
String) As Boolean
Dim sr As IO.StreamReader
Try
sr = New IO.StreamReader(IO.File.OpenRead(path))
Return (sr.ReadToEnd.IndexOf(searchPattern) > -1)
Catch ex As Exception
Return Nothing
Finally
sr.Close()
End Try
End Function

but I doubt that this would be faster then checking line by line and
breaking if a match occurs. That could be easily tested though...
 
KD,

Do you mean with text "text" or ".txt". Because the answers you have got now
are for ".txt".
For "text" there is not *one* method, because you don't know the format of
the saved file.

I hope this helps?

Cor
 
Thanks for the code.

kd

Diana Mueller said:
Well, you could do something like

Private Function FindInFile(ByVal searchPattern As String, ByVal path As
String) As Boolean
Dim sr As IO.StreamReader
Try
sr = New IO.StreamReader(IO.File.OpenRead(path))
Return (sr.ReadToEnd.IndexOf(searchPattern) > -1)
Catch ex As Exception
Return Nothing
Finally
sr.Close()
End Try
End Function

but I doubt that this would be faster then checking line by line and
breaking if a match occurs. That could be easily tested though...
 
Thanks

What would you suggest the recommended size of the .txt file, in order to use
'ReadToEnd'?

kd
 
I mean what would be the maximum size that you suggest for the .txt file in
order to use 'ReadToEnd'?

kd
 
kd said:
I mean what would be the maximum size that you suggest for the .txt file
in
order to use 'ReadToEnd'?

Some KB :-). Note that the file will be loaded into memory and thus the
memory usage will be incremented by at least the size of the file.
 
Herfried,
Some KB :-). Note that the file will be loaded into memory and thus the
memory usage will be incremented by at least the size of the file.
Amazing that you know that Hefried, however that is normal with fysical
memory.

With human memory it is something else especially when you have HKW memory.

:-)

Cor
 
Back
Top