Strings are problematic because they can be stored in different ways. They can be length prefixed, fixed size or null terminated.
For length prefixed strings use the standard BinaryReader.ReadString method.
For fixed size buffers read the entire data
into memory (or even as blocks) using BinaryReader.Read. After the string is in memory then convert it using Encoding.CharSet.GetString.
The CharSet used will depending upon how the string was saved (Unicode or ANSI). For fixed length strings there are probably padding characters added
to it so use String.TrimEnd to remove them.
For null terminated strings there is little option but to read the data one byte at a time, storing each byte into a byte array until you reach
a null. Then convert as though it was a normal string. Note for Unicode strings that you should look for two nulls.
string ReadBasicString ( BinaryReader reader )
{
&nbps;return reader.ReadString();
}
string ReadCStyleFixedSizeString ( BinaryReader reader, int size )
{
byte[] buffer = new byte[size];
reader.Read(buffer, 0, size);
string value = Encoding.ASCII.GetString(buffer, 0);
value = value.TrimEnd('\0');
return value;
}
string ReadNullTerminatedString ( BinaryReader reader )
{
int count = 0;
byte[] buffer = new byte[1024]; //Could use a dynamic buffer here but we'll keep it simple
byte value;
do
{
value = (byte)reader.ReadByte();
if (value != 0)
buffer[count++] = value;
} while (value != 0)
return Encoding.ASCII.GetString(buffer, 0);
}