MemoryStream

In this chapter you will learn:

  1. How to use MemoryStream

Using MemoryStream

using System; //from ja  v  a 2  s . com
using System.IO; 
   
class MainClass {   
  public static void Main() {   
    byte[] storage = new byte[255]; 
 
    MemoryStream memstrm = new MemoryStream(storage); 
 
    StreamWriter memwtr = new StreamWriter(memstrm); 
    StreamReader memrdr = new StreamReader(memstrm); 
 
    for(int i=0; i < 10; i++) 
       memwtr.WriteLine("byte [" + i + "]: " + i); 
 
    memwtr.WriteLine("."); 
 
    memwtr.Flush(); 
 
    Console.WriteLine("Reading from storage directly: "); 
 
    foreach(char ch in storage) { 
      if (ch == '.') break; 
      Console.Write(ch); 
    } 
 
    Console.WriteLine("\nReading through memrdr: "); 
 
    memstrm.Seek(0, SeekOrigin.Begin); // reset file pointer  
 
    string str = memrdr.ReadLine(); 
    while(str != null) { 
      Console.WriteLine(str); 
      str = memrdr.ReadLine(); 
      if(str.CompareTo(".") == 0) break; 
    }  
  }  
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Use Serializable attribute to mark a class
  2. Deserialize Object
Home » C# Tutorial » Stream
Stream classes
Text File Read
Text File write
Text File Create
Text File Append
Replace File Content
BinaryReader
BinaryWriter
FileStream Create
FileStream byte read and write
BufferedStream
Compare File
File Copy
File Copy with FileStream
MemoryStream
Object Serialization
String Writer