Hi,
Oh, I want to be able to read any file. I am old, from the ancient
times when a binary reader reading byte by byte could read any file.
Thanks.
Still you don't tell where it happens as asked by Tom.
My guess is that it happens at PeekChar. If you check
http://msdn.microsoft.com/en-us/library/system.io.binaryreader.peekchar.aspx
you'll see that ArgumentException happens when the char is not valid with
the current encoding. The trick is that BinaryReader is not "just" a binary
reader. It exposes an underlying stream as a binary stream but still use
some encoding( UTF8 by default).
If all you need is to read bytes does it work if you just use FileStream ?
Else you could pass the encoding used by your file as a parameter when
building the BinaryReader (Text.Encoding.Default ?).
The smallest code sample that repro the problem could also help (here likely
with a first section that writes the file). For example :
Sub Main()
Const Path As String = "Test.txt"
' Write
Dim fs As New FileStream(Path, FileMode.Create)
Dim bw As New BinaryWriter(fs)
For i As Integer = 0 To 1000
bw.Write(i)
Next
bw.Close()
fs.Dispose()
' Read
fs = New FileStream(Path, FileMode.Open)
Dim br As New BinaryReader(fs)
Do While br.PeekChar <> -1 ' <====== FAILS HERE
Debug.WriteLine(br.ReadChar)
Loop
br.Close()
fs.Dispose()
End Sub
If you use Dim br as New BinaryReader(fs,Text.Encoding.Default) it works. In
the first version, a value is written that is not valid UT8 character so it
fails later when using PeekChar. With the Text.Encoding.Default (which is
ANSI), all character values are valid and the problem goes away.