Results 1 to 3 of 3

Thread: How to use a StreamReader to read....

  1. #1
    Junior Member
    Join Date
    Feb 12
    Posts
    21

    How to use a StreamReader to read....

    How do I use a StreamReader to read the data (from a text file), parse it, and place it in a two dimensional array??

    The data:

    0,710,887,1130,525
    710,0,1510,1610,515
    887,1510,0,454,1070
    1130,1610,454,0,1110
    525,515,1070,1110,0

    Note: the first row of data contains the distances from location1 to all five locations, the second row of data contains the distances from location2 to all five locations, and so on.

  2. #2
    vb Coda .paul.'s Avatar
    Join Date
    May 07
    Location
    Chelmsford UK
    Posts
    16,508

    Re: How to use a StreamReader to read....

    using a streamreader:

    vb Code:
    1. Dim fileName As String = "filename.txt"
    2. Dim sr As New IO.StreamReader(fileName)
    3. Dim linesCount As Integer = sr.ReadToEnd.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries).Count
    4. sr = New IO.StreamReader(fileName)
    5. Dim array2D(linesCount - 1, 4) As Integer
    6. For l As Integer = 0 To linesCount - 1
    7.     Dim fields() As String = sr.ReadLine.Split(","c)
    8.     For x As Integer = 0 To fields.GetUpperBound(0)
    9.         array2D(l, x) = CInt(fields(x))
    10.     Next
    11. Next

  3. #3
    Fanatic Member AceInfinity's Avatar
    Join Date
    May 11
    Posts
    585

    Re: How to use a StreamReader to read....

    Quote Originally Posted by .paul. View Post
    using a streamreader:

    vb Code:
    1. Dim fileName As String = "filename.txt"
    2. Dim sr As New IO.StreamReader(fileName)
    3. Dim linesCount As Integer = sr.ReadToEnd.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries).Count
    4. sr = New IO.StreamReader(fileName)
    5. Dim array2D(linesCount - 1, 4) As Integer
    6. For l As Integer = 0 To linesCount - 1
    7.     Dim fields() As String = sr.ReadLine.Split(","c)
    8.     For x As Integer = 0 To fields.GetUpperBound(0)
    9.         array2D(l, x) = CInt(fields(x))
    10.     Next
    11. Next
    Remember to close/dispose of your StreamReader as well

    I would have just made use of the Using keyword for that.
    <<<------------
    < Please rate my post if this helped you out. Any kind of thanks is gladly appreciated >



    VB Programming (2012 - Present)
    ®Crestron - DMC-T Certified Programmer | Software Developer
    <<<------------

Posting Permissions

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