.NET/C# RichTextBox File Stream
This annoyed me for almost a day, and definitely deserves a reference article. I wrote a Win32 program in C/C++ that loads and sends a ANSI text file (ws2_32.lib/winsock2.h) to another .NET program. Receiving and storing the bytes in a local MS SQL CE database worked fine. It also worked fine retrieving it afterwards and putting it in a new text file. What did NOT work was to show it directly in a RichTextBox control:
Does NOT work:
// Get value from SQL server...
txtRichTextBox.Text = Encoding.ASCII.GetString((byte[])row[0]);
The RichTextBox control just shows a single space. With other encoding alternatives it was the same or just nonsense. After some debugging and thinking about how it only seems to work between files (reading from, writing to) I decided to try this:
DOES work:
MemoryStream MS = new MemoryStream();
byte[] tmpBytes;
// Get value from SQL server...
while (row.Read()) {
tmpBytes = (byte[])row[0];
MS.Write(tmpBytes, 0, tmpBytes.Length);
}
MS.Position = 0;
txtRichTextBox.LoadFile(MS, RichTextBoxStreamType.PlainText);
MS.Close();