0

I have a text file that has data line by line. I am trying to put the lines of data into an array or list.

    Dim req As WebRequest = WebRequest.Create("http://www.blahblah.com/data/ListFull.csv")
    Dim res As WebResponse = req.GetResponse()
    Dim stream As Stream = res.GetResponseStream()
    Dim sr As StreamReader = New StreamReader(stream, Encoding.ASCII)
    Dim streamString As String = sr.ReadToEnd

    '#1
    Dim lines1 As String()
    If streamString.Length > 0 Then
        lines1 = streamString.Split(vbLf)
    End If

    '#2
    Dim lines2 As New List(Of String)
    Using r As StreamReader = New StreamReader(stream, Encoding.ASCII)
        Dim line As String
        line = r.ReadLine
        Do Until String.IsNullOrEmpty(line)
            lines2.Add(line)
            'counter += 1
            'line = r.ReadLine
        Loop
    End Using

I have option one working fine, and all of the file data is going into my lines1 array.

Option 2 however is not working. When I step through the code: line = r.ReadLine is null/nothing. Why isnt the stream being read in and what am I doing wrong?

3
  • remove the comment tick from 'line = r.ReadLine : it works fine for me. The line sr.ReadToEnd would be used for the first thing only, since for the second since you want to read line by line. Commented Jan 14, 2016 at 16:02
  • Hello David, are you using both solutions in one function/parallel? You should work with "using" also in your first solution. Maybe the stream is already at the end of the file. Try to comment out solution1 and the assignement of the streamString. Commented Jan 14, 2016 at 16:12
  • 1
    Yes, they wont work together - #1 method will have already consumed the stream Commented Jan 14, 2016 at 16:14

1 Answer 1

1

After this line:

Dim streamString As String = sr.ReadToEnd

Your stream object is empty, all its content has been copied to the string and now "stream" doesn't contain anything. Some stream classes support:

Stream.Seek(0, SeekOrigin.Begin)

To go back to the beginning, but the Stream returned by GetResponseStream() does not support it.

You can either duplicate the Stream (I wouldn't recommend) or you can just process the streamString you have already retrieved.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.