Results 1 to 3 of 3

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

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Feb 2012
    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
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,416

    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 2011
    Posts
    696

    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.
    <<<------------
    Improving Managed Code Performance | .NET Application Performance
    < Please if this helped you out. Any kind of thanks is gladly appreciated >


    .NET Programming (2012 - 2018)
    ®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
  •  



Click Here to Expand Forum to Full Width