[Mono-list] read / write string to stream
kornelpal at gmail.com
Sun Apr 23 07:22:20 EDT 2006
The method you want to use to store strings is up to you but the class
library has support for lenght prefixed string encoding.
If you use Encoding.UTF8 with BinaryReader and BinaryWriter you will get a
very portable solution.
----- Original Message -----
From: "Abe Gillespie" <abe.gillespie at gmail.com>
To: "mono-list @ lists. ximian. com" <mono-list at lists.ximian.com>
Sent: Sunday, April 23, 2006 3:48 AM
Subject: [Mono-list] read / write string to stream
Is there a standard way to read and write strings from / to streams
such that the string's length prefixes the string or the string is
null-terminated? Or must this code be implemented by hand?
This is how I manually read a string from a stream. The string is
prefixed by its length:
// Get the length of the string.
byte data = new byte[sizeof(int)];
stream.Read(data, sizeof(int), tmpPtr);
int len = BitConverter.ToInt32(data, 0);
string myStr = "";
if (len > 0)
// Read in the string bytes.
data = new byte[len];
stream.Read(data, len, tmpPtr);
// Convert to a normal string.
myStr = Encoding.ASCII.GetString(data);
I do pretty much the opposite to write the string. I rather not do
this manually if there's already a standard way to.
Thanks for any help.
Mono-list maillist - Mono-list at lists.ximian.com
More information about the Mono-list