0

I am trying to read a file from my computer and output its contents into a literal control. It gives the 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. This is my first time using FileStream and I'm not 100% about all of the syntax for VB, or if there's even a community-preferred way of reading from a file, but could somebody help me out with this error?

This is the code:

 Using fs As New FileStream(_path, FileMode.Open, FileAccess.Read) Try Dim fileLength As Integer = CInt(fs.Length) Dim buffer() As Byte = New Byte() {fileLength} Dim count As Integer Dim sum As Integer = 0 While ((count = fs.Read(buffer, sum, fileLength - sum)) > 0) sum = sum + count End While litOutput.Text = buffer.ToString() Catch ex As Exception 'TODO: log error End Try End Using 
1
  • How about File.ReadAllText? There is also a version that takes an encoding. Commented Jul 2, 2015 at 16:57

1 Answer 1

1

This line is wrong

Dim buffer() As Byte = New Byte() {fileLength} 

It declares an array of 1 byte in which you try to store the length of your file. Probably you have Option Strict set to Off and thus you could go away without noticing immediately the problem.

Of course, if your file is of a reasonable length and it is a simple textfile then there is no need for this loop. Just use File.ReadAllText or File.ReadLines or File.ReadAllLines, and by the way, your code read all your data in a single call because the last parameter of FileStream.Read is the quantity of bytes to read from file and the expression fileLength - sum produces a request to read all the bytes in a single call

Instead if you want to read your file in chunks of certain sizes then probably you need

Using fs As New FileStream(path, FileMode.Open, FileAccess.Read) Try Dim chunkSize = 2000 Dim fileLength As Integer = CInt(fs.Length) Dim buffer(fileLength) as Byte Dim blockSize(chunkSize) as Byte Dim count As Integer = -1 Dim pos As Integer = 0 While count <> 0 count = fs.Read(blockSize, 0, chunkSize-1) Array.Copy(blockSize, 0, buffer, pos, count) pos += count End While litOutput.Text = Encoding.UTF8.GetString(buffer) Catch ex As Exception Console.WriteLine(ex.Message) End Try End Using 

Notice that this code assumes that your file is a Text file with UTF8 encoding.
It this is not the case then you could try with Encoding.ASCII.GetString or Encoding.Unicode.GetString

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

1 Comment

Thanks, had no idea File.ReadAllText was a thing. Much simpler!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.