[Mono-list] read / write string to stream

Abe Gillespie abe.gillespie at gmail.com
Sat Apr 22 21:48:25 EDT 2006


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.
-Abe


More information about the Mono-list mailing list