Convert MemoryStream to string using ASCIIEncoding - CSharp File IO

CSharp examples for File IO:MemoryStream

Description

Convert MemoryStream to string using ASCIIEncoding

Demo Code

using System;/*from w ww  .ja va  2 s. co m*/
using System.IO;
using System.Text;
public class Program
{
   public static void Main(string[] args)
   {
      string data = "test/ntest/ntest/n";  // \n equiv to 2 bytes, so 18 bytes.
      Console.WriteLine("Original data:\n{0}", data);
      byte[] buffer = new byte[data.Length + 20];
      MemoryStream ms = new MemoryStream(buffer);
      ASCIIEncoding encoding = new ASCIIEncoding();
      string dataInStream = encoding.GetString(ms.ToArray(), 0, ms.ToArray().Length);
      Console.WriteLine("Write the data in the stream as a string:\n{0}", dataInStream);
      Console.WriteLine("Read from the stream.\n");
   }
}

Result


Related Tutorials