[C#] Disapearing bytes

Got questions? Got answers? Go here for both.

Moderator: MaxCoderz Staff

Post Reply
King Harold
Calc King
Posts: 1513
Joined: Sat 05 Aug, 2006 7:22 am

[C#] Disapearing bytes

Post by King Harold »

In a little console program I had the idea to write some text to a MemoryStream (ASCII encoded). All goes well, until I try to write 1 byte to it: it just disappeared. It really was nowhere to be found.

To hide away the conversion from ASCII to bytes, I wrote this function:

Code: Select all

static void writeToStream(Stream s, string data)
{
       byte[] b = Encoding.ASCII.GetBytes(data);
       s.Write(b, 0, b.Length);
}
at some points, a byte is written like this:

Code: Select all

writeToStream(s, "<");
s.WriteByte((byte)lut[n.Name]);
writeToStream(s, ">");
Where lut is a Dictionary<string,int> containing all possibilities for n.Name (already tested not to overflow the byte).
The byte however is not in the stream at all, it's just gone..

Strangely enough, the single byte suddenly appears when it is written like this:

Code: Select all

writeToStream(s, "<<");
s.WriteByte((byte)lut[n.Name]);
writeToStream(s, ">");
The byte overwrite the second < for some reason (afaik, it shouldn't)

What am I missing here?
User avatar
benryves
Maxcoderz Staff
Posts: 3087
Joined: Thu 16 Dec, 2004 10:06 pm
Location: Croydon, England
Contact:

Re: [C#] Disapearing bytes

Post by benryves »

I suspect that you need to flush the stream between writes. Stream writers cache data as you write to them, so without explicitly flushing you can end up with missing or out-of-synch data.

Code: Select all

MemoryStream WorkingStream = new MemoryStream();

BinaryWriter BinaryData = new BinaryWriter(WorkingStream, Encoding.ASCII);
TextWriter TextData = new StreamWriter(WorkingStream, Encoding.ASCII);

TextData.Write("<<");
TextData.Flush();

BinaryData.Write((byte)0xFF);

TextData.Write(">");
TextData.Flush();
Personally, I'd just use a single BinaryWriter and be done with it.

Code: Select all

BinaryWriter BinaryData = new BinaryWriter(WorkingStream, Encoding.ASCII);

BinaryData.Write(Encoding.ASCII.GetBytes("<<"));
BinaryData.Write((byte)0xFF);
BinaryData.Write(Encoding.ASCII.GetBytes(">"));
King Harold
Calc King
Posts: 1513
Joined: Sat 05 Aug, 2006 7:22 am

Post by King Harold »

Alright that sounds like a good plan
Though I was only using the MemoryStream, without TextWriters (hence the method that converts to ASCII bytes and writes), I would say it's more than a bit odd that it would go out of sync with itself (all I ever do is write to it directly, but some bytes with Write and others with WriteByte)

I'll test flushing and BinaryWriter later today (first I have exams Imperative Programming), thank you for the ideas

edit: flushing doesn't help
Post Reply