We're a community of 1.1M IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,080,437 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

searching then reading a line in a text file

Right guys, I'm really new to this but I'm getting along ok, but I've hit a block.

I need to be able to know how to search a text file in VB for a particular line and then display it.
the files I'm trying to use are set up as: ID, Name, Address, Birthday, Pay-Roll Type
So I need to know how to search the file for the ID number and then display the rest of that line

I can read a file from beginning to end but this I am clueless about, thanks
It's for a system to add, display, update and remove workers

3
Contributors
16
Replies
1 Week
Discussion Span
1 Year Ago
Last Updated
19
Views
Question
Answered
BeeKeeper18
Newbie Poster
9 posts since Mar 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

One easy way is to use a filter as in

Dim alltext() As String = System.IO.File.ReadAllLines(myfilename)
Dim filtered() As String = Filter(text, "12345")

You may have to include the field delimiters (commas, perhaps) in the filter string to prevent matches on the ID string if it should happen to occur in another field.

Another possibility, if the fields are regular and delimited is to open the text file as a data source and use a SQL query to select the records of interest. I can help with that if you want to go the SQL route.

Reverend Jim
Illigitimae non carborundum
Moderator
3,740 posts since Aug 2010
Reputation Points: 585
Solved Threads: 469
Skill Endorsements: 33

thanks for your help, but I need the User to be able to enter an ID and it isn't the same each time, therefore the code would need adapting each time? The user needs to be able to input the ID in a text box and then locate the corresponding line in the text file

BeeKeeper18
Newbie Poster
9 posts since Mar 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

You can replace the string with something like

Dim filtered() As String = Filter(text, txtUserID.text)

Reverend Jim
Illigitimae non carborundum
Moderator
3,740 posts since Aug 2010
Reputation Points: 585
Solved Threads: 469
Skill Endorsements: 33

If you want to use the file as a data source it can be done using ADO as follows

Imports ADODB

Public Class Form1
    .
    .
    .
 
'assuming the user clicks on btnLogin after entering a userid

   Private Sub login_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles login.Click

        Dim con As New ADODB.Connection
        Dim rec As New ADODB.Recordset

        con.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & myFolder & ";Extended Properties='TEXT;HDR=YES;FMT=DELIMITED'")
        rec.Open("select * from " & myFile & " where ID='" & txtUsedID.Text & "'", con, CursorTypeEnum.adOpenForwardOnly)

        if rec.EOF Then
            'userID was not in the file
        else
            'userID was found
        End If
        
        rec.Close()
        con.Close()

    End Sub

Note the part of the connection string that states HDR=YES. This indicates that the first line of the file contains the names of the fields such as

"ID","Name","Address","Birthday","Pay-Roll Type"
"123","Ferguson, John","704 Hauser St.","1984-01-13","Hourly"
"902","Jefferson, George","East Side","1953-12-20","Salaried"

Reverend Jim
Illigitimae non carborundum
Moderator
3,740 posts since Aug 2010
Reputation Points: 585
Solved Threads: 469
Skill Endorsements: 33

You can replace the string with something like

Dim filtered() As String = Filter(text, txtUserID.text)

This piece of code won't work, I'm not sure why, it says string cannot be converted to 1 dimensional array of object and Include As Boolean = True, twice.

BeeKeeper18
Newbie Poster
9 posts since Mar 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

I used the following code with the sample data I posted above.

Private Sub login_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles login.Click

        Dim con As New ADODB.Connection
        Dim rec As New ADODB.Recordset

        con.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Temp;Extended Properties=""text;HDR=YES;FMT=Delimited""")
        rec.Open("select * from test.txt where ID='123'", con, CursorTypeEnum.adOpenForwardOnly)

        Do Until rec.EOF
            Debug.WriteLine(rec("ID").Value & " " & rec("Name").Value)
            rec.MoveNext()
        Loop

        rec.Close()
        con.Close()

It worked.

Reverend Jim
Illigitimae non carborundum
Moderator
3,740 posts since Aug 2010
Reputation Points: 585
Solved Threads: 469
Skill Endorsements: 33

This piece of code won't work, I'm not sure why, it says string cannot be converted to 1 dimensional array of object and Include As Boolean = True, twice.

I'd have to see the actual code that you ran, the exact error message and the contents of the text variables you included in the Filter call.

Reverend Jim
Illigitimae non carborundum
Moderator
3,740 posts since Aug 2010
Reputation Points: 585
Solved Threads: 469
Skill Endorsements: 33

I use this to check if a name in my file exists.

Dim names As String = ("C:\") 'location of your file
Dim lijst As New System.IO.StreamReader(names)
Dim namelist As String = lijst.ReadToEnd()
lijst.Close()
Dim lines() As String = Split(namelist, vbCrLf)
Dim line As String
For Each line In lines
If line = oldname Then
Label1.Text = line
End If
Next

Gé48
Junior Poster in Training
63 posts since Apr 2010
Reputation Points: 11
Solved Threads: 10
Skill Endorsements: 0

This won't work unless oldname is the only string on the line. According to your OP, the file format was " ID, Name, Address, Birthday, Pay-Roll Type". In the OP you said you were scanning for "ID". Now it appears you are scanning for "name", at least based on the comparison "if line = oldname Then". If you want to nail this down then I need you to be precise. Also, if you noticed I had suggested

Dim alltext() As String = System.IO.File.ReadAllLines(myfilename)

which reads all of the text file and splits it into an array of lines in one step. This works whether the lines are terminated by vbCrLf or just vbLf. Your way (using a streamreader and a Split) may not work for both cases.

Reverend Jim
Illigitimae non carborundum
Moderator
3,740 posts since Aug 2010
Reputation Points: 585
Solved Threads: 469
Skill Endorsements: 33

Sorry I was not clear enough, am new at this as well
In my case oldname is a string I read from a TextBox
You do the same with your ID
If you have got the line "ID, Name, Address, Birthday, Pay-Roll Type"
as a string already, you can try this:
Where yourstring is the name you use for "ID, Name, Address, Birthday, Pay-Roll Type"
It reads the total of numbers/letters in your TextBox and gets the same amount from
the left of yourstring where your ID is.

Dim check As String = TextBox1.Text
Dim tl As Integer = TextBox1.TextLength
Dim str as String = Microsoft.VisualBasic.Left(yourstring, tl)
If check = str Then
' whatever you want to do
End If

Gé48
Junior Poster in Training
63 posts since Apr 2010
Reputation Points: 11
Solved Threads: 10
Skill Endorsements: 0

My mistake. The link in the email took me to the bottom of the thread and I mistook the post from Ge48 as a post from the OP. Anyway, if the OP can please post a sample of the file being searched, and a sample of the text to search for I can post some specific code.

Reverend Jim
Illigitimae non carborundum
Moderator
3,740 posts since Aug 2010
Reputation Points: 585
Solved Threads: 469
Skill Endorsements: 33

My mistake. The link in the email took me to the bottom of the thread and I mistook the post from Ge48 as a post from the OP. Anyway, if the OP can please post a sample of the file being searched, and a sample of the text to search for I can post some specific code.

Imports System.IO
Public Class Form1
Private Sub BtnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnOpen.Click
Dim FileReader As StreamReader
Dim results As DialogResult
results = OpenFileDialog1.ShowDialog
If results = DialogResult.OK Then
FileReader = New StreamReader(OpenFileDialog1.FileName)
IDFilter.Text = FileReader.ReadToEnd()
FileReader.Close()
End If
End Sub

The text I am trying to search is layed out like so:

094,Frickerman,21 Nicols Road,Canterbury,CT9 3RD,12/12/1981,07 March 2012,Gold
095,Oppern,1 Zion Place,Wye,CT9 1RP,13/01/1974,13 March 2012,Gold

So I want to able to search for 095 and only display:
095,Oppern,1 Zion Place,Wye,CT9 1RP,13/01/1974,13 March 2012,Gold

CurrentlyI can only display the whole text file not the particular line that I want.
Apologies if I'm not being very useful

BeeKeeper18
Newbie Poster
9 posts since Mar 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

You wouln't be able to use the ADO method because the fields aren't enclosed in quotes. The address field contains commas and these would be interpreted as field separators. I think the Filter option is your best bet. Read the entire file into a string array then filter on the ID plus a comma. Because this may also match something in the address portion you will still have to do a check on every line in the FIlters array to see if a line starts with the required string.

Dim alltext() As String = System.IO.File.ReadAllLines("d:\temp\test.txt")
Dim lookfor As String = "095" & ","

For Each line As String In Filter(alltext, lookfor)
    If line.StartsWith("095,") Then
        MsgBox("found " & line)
    End If
Next

I create the search string (lookfor) by concatenating an ID value with a comma. You will have to replace "095" with the variable (or textbox.Text object) containing the ID you are looking for. The "Filter" call reduces the array to only those lines containing <lookfor> in any position and the For loop find the line beginning with that value.

Reverend Jim
Illigitimae non carborundum
Moderator
3,740 posts since Aug 2010
Reputation Points: 585
Solved Threads: 469
Skill Endorsements: 33
Question Answered as of 1 Year Ago by Reverend Jim and Gé48

You wouln't be able to use the ADO method because the fields aren't enclosed in quotes. The address field contains commas and these would be interpreted as field separators. I think the Filter option is your best bet. Read the entire file into a string array then filter on the ID plus a comma. Because this may also match something in the address portion you will still have to do a check on every line in the FIlters array to see if a line starts with the required string.

Dim alltext() As String = System.IO.File.ReadAllLines("d:\temp\test.txt")
Dim lookfor As String = "095" & ","

For Each line As String In Filter(alltext, lookfor)
    If line.StartsWith("095,") Then
        MsgBox("found " & line)
    End If
Next

I create the search string (lookfor) by concatenating an ID value with a comma. You will have to replace "095" with the variable (or textbox.Text object) containing the ID you are looking for. The "Filter" call reduces the array to only those lines containing <lookfor> in any position and the For loop find the line beginning with that value.

Thank you for your help, do you know how I would adapt this code so I could remove or edit an individual line?

BeeKeeper18
Newbie Poster
9 posts since Mar 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

Arrays aren't great when it comes to removing items. Fo9r that you may be better off with a dictionary. It's a tiny bit more trouble to build but it is easier to check if an ID exists. For example:

Private records As New Dictionary(Of String, String)

    Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click

        Dim key As String

        For Each line As String In System.IO.File.ReadAllLines("d:\temp\test.txt")
            If InStr(line, ",") > 0 Then
                key = line.Substring(0, InStr(line, ",") - 1)
                records(key) = line
            End If
        Next

        If records.ContainsKey("095") Then
            MsgBox("found")
        End If

    End Sub

If you want the key to be an integer then declare as Dictionary(Of Integer, String) and convert the key before addind the new entry.

Reverend Jim
Illigitimae non carborundum
Moderator
3,740 posts since Aug 2010
Reputation Points: 585
Solved Threads: 469
Skill Endorsements: 33

I've never used dictionarys before, and my whole program is set up to use arrays. thanks for the help though

BeeKeeper18
Newbie Poster
9 posts since Mar 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page generated in 0.1193 seconds using 2.76MB