开发者

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

开发者 https://www.devze.com 2023-04-01 01:30 出处:网络
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 St

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 wi开发者_Python百科th 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.


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()));
        }


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.


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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消