search text files -

Is it possible to search text files contain a specific word. If found that specific word then add file name to a list box.

Last Name    : test
First Name    : test
Residence    : Bad address     ++++++++++++this is the line I am looking for and the word is "Bad address" +++++++++++++++++++++++

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

> Is it possible to search text files contain a specific word
The general concept is to read the file into a string (or string array), and search it from there.

[can't really help with the code though]
VBdotnet2005Author Commented:
thanks Interactivemind - I know you hate the language.
lol ;-)

Snooping round the MSDN--I get:

   Dim search_term As String = "your search term"
   Dim sContents As String = GetFileContents("C:\test.txt", sErr)
   Dim flag As Integer = sContents.IndexOf( search_term, 0, sContents.Length )
   If flag >= 0
      ' The search_term exists in the file
   End If
CompTIA Security+

Learn the essential functions of CompTIA Security+, which establishes the core knowledge required of any cybersecurity role and leads professionals into intermediate-level cybersecurity jobs.

But I suspect that I've missed somethings out there--so I'll stop trying ;-)

Good luck with it
VBdotnet2005Author Commented:

good sample - different approach

I was thinking about spliting each line/word (for example   Residence    :  bad address)  What do you think?

 dim sr as new streamreader("c\whatever.txt")
  dim linevalue as string
  dim myArrays as array
  dim listname as string
  dim listaddress as string
  linevalue = mysr.readline()
  while linevalue<> nothing
   myarrays = linevalue.split(":")
   listname = Ucase(trim(myarray(0))
   select case (listname)
    case "RESIDENCE"
    listaddress = ucase(trim(myarray(1))
    If myarray(1) = " Bad Address" then
        listbox1.items.add +++++++++++++++++++++++ not sure right here++++++++++++++++++++
   end select
  linevalue = sr.readline()
Presuming you want to kick out as soon as you find the first 'not found', I'd keep it simple with something like:
(Like IM, I'm not much of a VBer, so I won't try to give syntactically correct code)

linevalue = mysr.readline()
while linevalue<> nothing
         if left(cleanedup),9)="RESIDENCE"  
            if  0> cleanedup.indexof(": NOT FOUND")


if you are using a stream reader then u dont need to do line by line reading since the stram reader is providing a method for reading all of of the content to the memory.
here is a simple function i wrote to check a file contains a specific word. hope this will help to fix the problem

    Private Function IsFileContainsSrting(ByVal SearchWord As String, ByVal FileName As String) As Boolean
        Dim IsWordFound As Boolean = False
        Dim FileContents As String = String.Empty
        Dim FileStreamReader As StreamReader
            FileStreamReader = New StreamReader(FileName)
            FileContents = FileStreamReader.ReadToEnd()
        Catch ex As Exception
            IsWordFound = False
            If Not (FileStreamReader Is Nothing) Then
            End If
        End Try
        If FileContents.IndexOf(SearchWord) > 0 Then
            'IndexOf returns -1 of not found and 0 if the textVal is empty
            IsWordFound = True
        End If
        Return IsWordFound
    End Function

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
The reason for reading line by line, instead of the entire file, is that the first instance of 'Not Found' seems to be all that matters.  
I would use Instr function.

Works something like this.

Instr(Thetexttosearch, "Bad Address")

The return value is an integer. It will tell you what character number it is.

Example: 156

Then you know where Bad Address starts, then just trace over to the left. If Bad Address can't be found it returns 0

Soooo...I don't know, that's the technique I use.
> "If Bad Address can't be found it returns 0"
But 0 would be the very start of the search string--so would that not be a number less than 0 (e.g. -1) ?
Screw something like;

Dim SomeString as string
Dim LookForBad as integer
Dim TheFile as string

The file = 'something in here
Dim sContents As String = GetFileContents(TheFile, sErr)

SomeString = Scontents
LookForBad = instr(somestring, "Bad Address")

If LookForBad > 0 then
end if

That should do it, assuming you already know how your calling each file. If you don't know then tell me the function of the program, I'll help you out.
No 0 is not the start. 1 is the start.
The 'instr' VB6 function does, indeed, start at 1.  

The VB.NET string.IndexOf() method starts at 0 and returns -1 if not found.

I haven't the slightest idea if VB.NET recognizes 'instr'.
Well, I can't find any docs on it, in the MSDN.

Any guesses why it starts at 1? (I suppose that 'n00b' programmers find it difficult to grasp 0 being the first index?) ... do arrays in VB6~ start at 1 also?
Lordy, which MSDN have you been going to?

This is on my Firefox bookmark toolbar:

whose search box yielded:

For those of us who have followed the route: B-Box -> index register -> offset, zero-based arrays certainly seem The Natural Order Of Things.  The Basic world, however, was intended to simplify things, whence 1-based counting.  Once that was established, woe betide the interpreter/compiler writer who didn't support all that extant 1-based code.

On the off chance you don't read Joel On Software, this brings to mind his latest column:

The Perils of JavaSchools

Go search around EE for questions about folks being mystified when their code displays 1.9999999999 instead of 2 (along with some rather outrageous 'answers'), and you'll see the problem he's talking about.

No. It starts at 1. It always has. Tell me, logically, why would it start at 0? Then it would have to return -1 if the string wasn't found. It however returns 0 if the string isn't returned, for simplicity sake.

At worked, I programmed a log translation program where the log is basically just Jibberish to the untrained eye. So my program searches for certain strings that are patterns inside the log, and creates a comma delimited file for excel. (Using Instr)

If you don't believe me, go into, and place this into a button.

    Dim x As String
        Dim y As Integer
        x = "Hello"
        y = InStr(x, "H")

y will return 1

If you change "H" to "e" it will return 2.

<stares gaumlessly at cookre, and scratches head />
Well, it's a bloody good thing that I've learnt pointers ;-)

Brant, perhaps you should escape your VB-bubble.
You've misinterpreted what I've been saying, and have become very defensive..

Me>> "Well, I can't find any docs on it, in the MSDN."
That was in response to cookre's comment, "I haven't the slightest idea if VB.NET recognizes 'instr'.".
Clearly however, I had overlooked it.

VB is probably the first language that I have/recall coming across, that uses 1 as the base.. Gosh, even MS-DOS batch scripts use 0 as the base for strings !

While being quite a Java-fanatic myself, and therefore perhaps sounding somewhat contradictive: I think that you should read that "Joel on Software" article..

I can honestly say that I'm not in a bubble..
I'm not being defensive. Defensive of a point I was trying to make maybe...which you were right, I must have missed what you said. It doesn't look like you were even talking about the function Instr at all. You will have to excuse me, lack of sleep brings my reading comprehension and spelling down to a 6 year old's level :-D


I do not wish to offend you or anyone else, infact I do believe you are one of the brightest minds here on Experts-exchange, and I know very soon I will be looking to call upon your knowledge.

It's no problem--I didn't see anything offensive in your comment. Just misunderstanding.

> infact I do believe you are one of the brightest minds here on Experts-exchange
lol I wish I could agree. But thanks for the vote of confidence.

Well, I'm off to bed now.

Happy new year, all.
VBdotnet2005Author Commented:
VB 6 uses 1 as the base, but uses  zero as the base. Instr is VB6, where indexof is, my understanding. Correct?
VBdotnet2005Author Commented:
Thank you all. " I'm off to bed now."
How to Match whole word ?
Here i mean if content is like "This is a bal'"
and i m finding "is" then it will also return true for "This" also.

please suggest.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.