Tarik
Tarik

Reputation: 81721

Read and Write a String in/from Stream without Helper Classes

Lets say I wanna write a string "Hello World" into a MemoryStream and read this string to MessageBox.Show() without using Helper objects such as BinaryWriter and BinaryReader and StreamWriter and StreamReader etc.

Can you show me how to accomplish this with low-level functions of MemoryStream stream object.

P.s: I both use C# and VB.NET so, please feel free to use either of them.

Thanks.

Upvotes: 2

Views: 508

Answers (3)

Efran Cobisi
Efran Cobisi

Reputation: 6454

You will have to choose a text encoding and use it to grab the data:

        var data = "hello, world";

        // Encode the string (I've chosen UTF8 here)

        var inputBuffer = Encoding.UTF8.GetBytes(data);

        using (var ms = new MemoryStream())
        {
            ms.Write(inputBuffer, 0, inputBuffer.Length);

            // Now decode it back

            MessageBox.Show(Encoding.UTF8.GetString(ms.ToArray()));
        }

Upvotes: 2

Davide Piras
Davide Piras

Reputation: 44605

Check this one: http://msdn.microsoft.com/en-us/library/system.io.memorystream.write.aspx

// Create the data to write to the stream.
byte[] firstString = uniEncoding.GetBytes("Hello World");

using(var memStream = new MemoryStream(100))
{
  memStream.Write(firstString, 0 , firstString.Length);
}

Upvotes: 1

Ignacio Soler Garcia
Ignacio Soler Garcia

Reputation: 21855

Just use System.Text.ASCIIEncoding.ASCII.GetBytes("your string) and write the resulting byte array to the stream.

Then, to decode the string use System.Text.ASCIIEncoding.ASCII.GetString(your byte array).

Hope it helps.

Upvotes: 2

Related Questions