Finding a string in a streamReader

I need to open a text file and check to make sure that a value I have already identified (strObject) can be found anywhere in the file.  So what I have looks like:
Dim ObjectReader As New StreamReader("C:\Adtrav\UAB\OBJECT.TXT")
            Dim lineRead As String
            Dim objectPresent As Boolean
            Try
                Do Until Microsoft.VisualBasic.Left(lineRead, 7) = strObject
                    lineRead = ObjectReader.ReadLine()
                Loop
            Catch
                MsgBox("Can't find Object")
            Finally
                ObjectReader.Close()
            End Try

Dont pay too much attention to the try catch piece as I dont really know  what I was doing there.  The only reason I am using readLine methods is because I cant seem to find a method that will just search the entire text block and find a string that I tell it to search for.  If there is a method like this please let me know.  But somehow or another I need to check the text file and see if I cant find a string.  Right now my Do Until Loop will go into an unterminating loop if if cannot find the string I tell it to look for.  So if I am doing this the best way by using a loop to run through each line what do I do to make what I have above correct, or is there a better way to simply search the entire stream for strObject?  Very urgent!
jacobymattAsked:
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.

Mike TomlinsonMiddle School Assistant TeacherCommented:
Here is a function that will return true if the value passed in is present in fileName:

    Private Function fileContainsString(ByVal fileName As String, ByVal value As String) As Boolean
        Try
            Dim sr As New StreamReader(fileName)
            Dim entireFile As String = sr.ReadToEnd
            sr.Close()
            Return entireFile.IndexOf(value) <> -1
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")
            Return False
        End Try
    End Function

~IM
0

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
jacobymattAuthor Commented:
Something wasnt working right so I wrote this test piece of code and it doesnt work correctly either, can you see what is wrong:

Dim dbConn As New OleDbConnection
    Dim ds As New DataSet
    Public dbAdapt As New OleDbDataAdapter

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        dbConn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=C:\Full Access\UAB\uab.mdb"
        Dim myCommand As New OleDbCommand
        myCommand.Connection = dbConn
        myCommand.CommandText = "SELECT * From UAB"
        dbAdapt.SelectCommand = myCommand
        dbAdapt.Fill(ds, "UAB")
        Dim DtUAB As DataTable = ds.Tables("UAB")

        Dim dvUAB As DataView = DtUAB.DefaultView
        Dim dvRow As DataRowView
        For Each dvRow In dvUAB
            Dim strObject As String = Microsoft.VisualBasic.Right(dvRow.Item(19), 7)
            'Dim strObject As String = "8302040"
            If Check_values("C:\Adtrav\UAB\OBJECT.TXT", strObject) = False Then
                MsgBox("Error: Object Code not found in file.")
            Else
                MsgBox("success!")
            End If
        Next
    End Sub

Public Function Check_values(ByVal fileName As String, ByVal value As String) As Boolean
        Try
            Dim ObjectReader As New StreamReader(fileName)
            Dim entireFile As String = ObjectReader.ReadToEnd
            ObjectReader.Close()
            Return entireFile.IndexOf(value) <> -1
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error: Object Code " & value & " not found in " & fileName & ".")
            Return False
        End Try
    End Function

The value I need to look for is always the right 7 digits of the 20th column in my Access table so you can see where I loop through the rows checking each time to see if that value is in the object.txt file.  I made all of the values the same in my access table and also a value that was in the object.txt so it would go through the first time showing only a message box of success for each row, but instead when I ran it I got 1 message boxes with "Error: Object Code not found in file." and then 18 more msgboxes with "success".  Then I changed one value in the access table to see if it would change the result and it performed the exact same way. Increasing points,  what is wrong with my logic?
0
Mike TomlinsonMiddle School Assistant TeacherCommented:
I'm not sure what is wrong with your code as I'm not too experienced in database code.  The function I wrote does work as advertised though so make sure you don't have any upper/lower case mismatches and that the item you are searching for is what you expected.  Also check the text file to make sure it looks as you expect.

~IM
0
rdrunnerCommented:
Hello,

jacobymatt, you could speed up your code very much. You are doing "useless" IO operations inside a "for each" loop. You should consider moving the code that actually reads your file out of the inner function and into the form load event. There is no reason to read the file 100 times from disk if there are 100 lines. Just read the file once and pass it as a variable to the function that does the comparrison.

I am lazy and i consider this a good trait of mine... I try to avoid "useless" work and i try to use the same logic against my software... It really helps sometimes :)
0
jacobymattAuthor Commented:
You guys both helped, here is what I ended up doing:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            Dim ObjectReader As New StreamReader("C:\Adtrav\UAB\OBJECT.TXT")
            objectFile = ObjectReader.ReadToEnd
            ObjectReader.Close()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error: Can't find Object.txt.")
        End Try
        Try
            Dim ASBOFReader As New StreamReader("C:\Adtrav\UAB\ASBOF.TXT")
            asbofFile = ASBOFReader.ReadToEnd
            ASBOFReader.Close()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error: Can't find ASBOF.txt.")
        End Try
        Try
            Dim PTAOReader As New StreamReader("C:\Adtrav\UAB\PTAO.TXT")
            ptaoFile = PTAOReader.ReadToEnd
            PTAOReader.Close()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error: Can't find PTAO.txt.")
        End Try
    End Sub

For Each dvRow In dvUAB
            strObject = Microsoft.VisualBasic.Right(dvRow.Item(19), 7)
            Label1.Text = Microsoft.VisualBasic.Right(dvRow.Item(19), 7)
            'Dim strObject As String = "8302040"
            If Check_values(objectFile, strObject) = False Then
                MsgBox("Error: Object Code not found in file." & strObject)
                ErrorLog += "Object Code " & strObject & " not found in Object.txt!" & vbCrLf
            Else
                'MsgBox("success!" & strObject & "")
            End If

            Select Case Len(dvRow.Item(19))
                Case 31
                    strPtao = Microsoft.VisualBasic.Left(dvRow.Item(19), 23)
                    If Check_values(ptaoFile, strPtao) = True Then
                        'MsgBox("success!" & strPtao & "")
                    Else
                        MsgBox("Error: GL Number " & strPtao & " was not Found in PTAO.txt")
                        ErrorLog += "GL Number " & strPtao & " not found in PTAO.txt!" & vbCrLf
                    End If
                Case 44
                    strAsbof = Microsoft.VisualBasic.Left(dvRow.Item(19), 36)
                    If Check_values(asbofFile, strAsbof) = True Then
                        'MsgBox("success!" & strAsbof & "")
                    Else
                        MsgBox("Error: GL Number " & strAsbof & " was not Found in Asbof.txt")
                        ErrorLog += "GL Number " & strAsbof & " not found in ASBOF.txt!" & vbCrLf
                    End If
                Case Else
                    ErrorLog += "Error: " & dvRow.Item(19) & ": Code is not proper Length" & vbCrLf
            End Select

Public Function Check_values(ByVal filestream As String, ByVal value As String) As Boolean
        Try
            Return filestream.IndexOf(value) <> -1
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error: Object Code " & value & " not found in " & filestream & ".")
            Return False
        End Try
    End Function
0
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
Visual Basic.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.