I'm trying to read mixed data (text & binary) from a network stream. The data format i have chosen is similar to the mail format:
(Text in Brackets [ ] is substituted with appropriate data)
Date: [DateTime UTC]
Content-Part-Count: [Part Count];
[Message Text goes here]
Content-MD5Checksum: [MD5 Checksum]
[PartData (can be binary)]
Reading the text part is easy. StreamReader.ReadLine() does the trick. However, when I come to the data parts, I'm switching to the BinaryReader. Since both readers use the underlaying NetworkStream I can use either one and be at the correct position within the stream. The problem occurs when I'm trying to read the binary data. I first read the "Content-Length" header of the part and then read the byte amount of that from the stream. I'm just reading the data from the stream, adding it to a byte array as we read. Since I'm reading over the network (Internet), I'm looping until I have read the right amount of bytes from the stream, then switching back to the StreamReader to read the next part, if there is one.
Having tried various things, I always seem to end up a few bytes short of data on the reciever side.
This is the code used to read the binary part of the message:
// read the data from the NetworkStream
// now read the data part
// read "Content-Length" from the header HashTable
int datalength = int.Parse(datapacket.GetHe
// create the byte array to hold the binary data
byte data = new byte[datalength];
int bytesRead = 0;
int bytesToRead = datalength;
int totalBytesRead = 0;
// set a timeout so we don't wait forever
TimeSpan timeout = new TimeSpan(0, 0, 5, 0, 0);
DateTime starttime = DateTime.Now;
// create the binary reader
BinaryReader datareader = new BinaryReader(networkStream
// read until we have read all we need or until we readched our timeout
while((bytesToRead > 0) && (starttime.Add(timeout) > DateTime.Now))
// read as long
bytesRead = datareader.Read(data, bytesRead, bytesToRead);
totalBytesRead += bytesRead;
bytesToRead = datalength - totalBytesRead;
// reset the timeout
starttime = DateTime.Now;
// let other processes do some work
// check the data (MD5 checksum, length, etc.)
All my tries have failed. I always have about 430 bytes left to read (bytesToRead), even though the stream should contain a few bytes more than the binary data part. There should be a "------=_NextPart_[Hash]--
" and a newline following.
Any ideas on what might be wrong?
The MSDN KnowledgeBase has an article on a bug in the BinaryReader.ReadChar() function at http://support.microsoft.com/default.aspx?scid=kb;en-us;318121
- Maybe this could be something similar?
Thanks for the help!