Solved

Finding a string in a streamReader

Posted on 2004-10-25
460 Views
Last Modified: 2008-03-10
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!
0
Question by:jacobymatt
    5 Comments
     
    LVL 85

    Accepted Solution

    by:
    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
     

    Author Comment

    by:jacobymatt
    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
     
    LVL 85

    Expert Comment

    by:Mike Tomlinson
    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
     
    LVL 11

    Assisted Solution

    by:rdrunner
    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
     

    Author Comment

    by:jacobymatt
    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

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Threat Intelligence Starter Resources

    Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

    This tutorial demonstrates one way to create an application that runs without any Forms but still has a GUI presence via an Icon in the System Tray. The magic lies in Inheriting from the ApplicationContext Class and passing that to Application.Ru…
    1.0 - Introduction Converting Visual Basic 6.0 (VB6) to Visual Basic 2008+ (VB.NET). If ever there was a subject full of murkiness and bad decisions, it is this one!   The first problem seems to be that people considering this task of converting…
    In this Experts Exchange video Micro Tutorial, I'm going to show how small business owners who use Google Apps can save money by setting up what is called a catch-all email address in their Gmail accounts. By using the catch-all feature, small busin…
    how to add IIS SMTP to handle application/Scanner relays into office 365.

    934 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now