Detecting an invalid char

726 views Asked by At

When reading chars from binary file with BinaryReader, I often come across malformed data that cannot be read as a char. I get an ArgumentException thrown.

Is there any way for me to anticipate when the next character will throw an exception so instead of trying to read it (which will throw an exception) to be able to deal with it without the costly operation?

BinaryReader.ReadChar();

Which inputs will cause ArgumentException to be thrown?

1

There are 1 answers

0
Karlovsky120 On

Ahh, just figured it out:

char next = (char)reader.ReadByte();

if (Char.IsSurrogate(next)) {
    return "Non-valid char value";
}

Feel free to post a better solution.