Results 1 to 4 of 4

Thread: How to read text file line by line?

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Apr 2010
    Posts
    131

    Question How to read text file line by line?

    Ok, I saw this code on the net

    Dim sFileName As String
    Dim srFileReader As System.IO.StreamReader
    Dim sInputLine As String

    sFileName = "D:\Users\Arben\Desktop\SerieA.txt"
    srFileReader = System.IO.File.OpenText(sFileName)
    sInputLine = srFileReader.ReadLine()
    Do Until sInputLine Is Nothing

    System.Console.WriteLine(sInputLine)
    sInputLine = srFileReader.ReadLine()

    Loop
    Now, I have some labels that I want the text on each of them to be the text on each line of the .txt file

    now I write this
    Label21.Text = sInputLine
    Label22.Text = sInputLine
    Label23.Text = sInputLine

    under the code I pasted at the top, but I get the text on line1 in all labels, like all labels become 1, while the text should be 1, 2, 3 and so on. So anyone can help me do that, each label gets the value of the next line in the txt file

  2. #2
    Lively Member
    Join Date
    Jun 2010
    Posts
    94

    Re: How to read text file line by line?

    all 3 labels are using the same variable, and it never changes which line to read

  3. #3
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,423

    Re: How to read text file line by line?

    try this:

    vb Code:
    1. dim lblCounter as integer = 1
    2.  
    3. Do while srFileReader.peek <> -1
    4.     'this will ouput text to label1, label2...etc
    5.     me.controls("Label" & lblCounter.tostring).text = sInputLine
    6.     lblCounter += 1
    7.     System.Console.WriteLine(sInputLine)
    8.     sInputLine = srFileReader.ReadLine()
    9.  
    10. Loop
    Last edited by .paul.; Sep 19th, 2010 at 06:35 PM.

  4. #4
    Fanatic Member
    Join Date
    Aug 2010
    Posts
    624

    Re: How to read text file line by line?

    @ paul you might want to check if the form actually contains a label of that name just in case. Also, using/endusing for streamreaders are a lot easier

    vb Code:
    1. Using sRead As New IO.StreamReader("D:\Users\Arben\Desktop\SerieA.txt")
    2.       Dim thisLine as string = ""
    3.       Dim nLabel as Integer = 0
    4.       Do Until sRead.EndOfStream
    5.           thisLine = sRead.ReadLine
    6.           if Me.Controls.ContainsKey("Label" & nLabel) then
    7.                Me.Controls("Label" & nLabel).Text = thisLine
    8.           End if
    9.           nLabel += 1
    10.        Loop
    11. End using

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width