I'm currently working on a demo file parser for a game I play. I've been looking at the format and the example given which is in PHP (trying to convert it to C#) but it uses fgetc which from what I can tell isn't available in C#, only C++. Any ideas how I can work around this? I've tried using StreamReader.Read() but it doesn't like null values.
The example can be found here if anyone wanted to take a look at the full script to get a better idea of what I'm trying to achieve.
Thanks!
You'll want to use a BinaryReader to read that file. To read int
, you can call ReadInt32
. To read their strings, you'll need to read byte-by-byte ReadByte
and compare with 0.
using (var fs = File.OpenRead(filename))
{
using (var reader = new BinaryReader(fs))
{
// reading happens here
}
}
private string ReadString(BinaryReader reader) { byte b; StringBuilder sb = new StringBuilder(); while ((b = reader.ReadByte()) != 0) { sb.Append((char)b); } return sb.ToString(); }
I made a mistake in converting the code. The file format says that the string will be 260 characters long. So you need to read 260 bytes and then trim the string, like this:
private string ReadString(BinaryReader reader, int length = 260)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; ++i)
{
byte b = reader.ReadByte();
sb.Append((char)b);
}
return sb.ToString().Trim();
}
To read the header, you would write:
string hldemo = ReadString(reader, 8);
and to read the host name, for example, it would be:
string host = ReadString(reader);
That's pretty much an exact duplicate of the php code, I think. See the format document for other string lengths, and look at their sample code. I might have missed something.