StreamReader Read?

  • Thread starter Thread starter Arpan
  • Start date Start date
A

Arpan

The contents of a text file are as follows:

The Quick Brown
Fox Jumped Over
The Lazy Dog.

Note that there isn't any space at the end of each of the 3 lines.

Now when I do this:

Sub Page_Load(ByVal obj As Object, ByVal ea As EventArgs)
Dim arrString(10) As Char
Dim strmReader As StreamReader

strmReader = New StreamReader(Server.MapPath("StreamReader.txt"))
strmReader.Read(arrString, 4, 8)
Response.Write("Array: " & arrString)
End Sub

ASP.NET generates the following error:

Offset and length were out of bounds for the array or count is greater
than the number of elements from index to the end of the source
collection.

pointing to the following line:

strmReader.Read(arrString, 4, 8)

But if I replace the offending line with this:

strmReader.Read(arrString, 4, 7)

i.e. change the last parameter of the Read method from 8 to 7, then the
Response.Write outputs the following in the browser:

Array: The Qui

Can someone please explain me why does the Read line in the first case
generate the error?

Secondly, if I replace the Response.Write line shown above with

Response.Write(arrString)

i.e. get rid of the string within the double quotes (preceding the
variable arrString) in the Response.Write line, then the
Response.Write(arrString) line doesn't generate any output in the
browser. Why so?

Thanks,

Arpan
 
You missunderstand how Read works.
(although, in fairness, the documentation is not overly clear).

read(buffer, index, count).

Read read count characters from the buffer into INDEX of the array.

You are trying to read 4 characters and placing it STARTING at index 8 of
your array. That means you'll insert "T" in spot 8, "h" in spot 9 and then
you're at the end of your array and trying to read 2 more characters.


As an example, try to prepopulate your array to see how it behaves:

Dim arrString() As Char = "1234567890".ToCharArray()
Dim strmReader As StreamReader

strmReader = New StreamReader(YOUR_FILE)
strmReader.Read(arrString, 4, 2)

you'll see that arrString ends up being 1234Th7890


As for your 2nd problem, you need to turn your char array into a string, you
can do that with: new string(arrString), something like:
Response.Write("Arrary: " & new string(arrString))

Karl
 
Back
Top