Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Finding a string in a streamReader

Posted on 2004-10-25
5
Medium Priority
?
485 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
Comment
Question by:jacobymatt
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
5 Comments
 
LVL 86

Accepted Solution

by:
Mike Tomlinson earned 400 total points
ID: 12403794
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
ID: 12407237
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 86

Expert Comment

by:Mike Tomlinson
ID: 12407675
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
rdrunner earned 200 total points
ID: 12408686
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
ID: 12415608
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

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Kraeven
Introduction Remote Share is a simple remote sharing tool, enabling you to see, add and remove remote or local shares. The application is written in VB.NET targeting the .NET framework 2.0. The source code and the compiled programs have been in…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Despite its rising prevalence in the business world, "the cloud" is still misunderstood. Some companies still believe common misconceptions about lack of security in cloud solutions and many misuses of cloud storage options still occur every day. …
Suggested Courses

610 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