Limitations of System.IO.StreamWriter in .NET 2.0
I was trying to deserialise a class from a string using the SoapFormatter today.
As part of the process, you have to put it into a stream.
So I used System.IO.MemoryStream and System.IO.StreamWriter to do so.
StreamWriter sw = new StreamWriter(stream);
sw.Write(strData);
stream.Position = 0;
But the deserialise kept failing.
The error message indicated that the XML was incomplete, but the string was fine.
strData.Length = 12763
stream.Length = 10240
Hmm 10240 = 10 x 1024 or 10KB, just a bit coincidental.
I did some Google searches, and quite a few sites had MemoryStream stream = new MemoryStream(10240); as example code.
So I thought maybe it was a limit in the MemoryStream class. But MSDN didn't mention it.
So I looked at the MemoryStream class using .NET Reflector. And I couldn't see any reason for a 10K limit.
So I looked at StreamWriter. I couldn't see anything there either. But on a hunch I changed
sw.Write(strData);
to
sw.Write(strData, 0, 6000);
sw.Write(strData, 6000, strDta.Length - 6000);
And behold, it began to work.
So I replaced that with:
int index = 0;
while(index < (strData.Length - 6000)) {
sw.Write(strData, index, 6000);
index += 6000;
}
if(index < strData.Length) {
sw.Write(strData, index, strData.Length - index);
}
And now everything is happy.
I'm not sure if this applies in .NET 1.X as I've never had it happen there.