Read and write with in memory with MemoryStream in CSharp

Description

The following code shows how to read and write with in memory with MemoryStream.

Example


 //from w  w w .  j  a  va  2  s  .  c  o  m
using System; 
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.





















Home »
  C# Tutorial »
    IO »




File Attribute
File Security
Directory Attribute
Directory Recursive
Binary File
Text Field
Buffered IO
Create Copy Delete Move
CSV
Drive
File System Watcher
Isolated Storage
MemoryStream
Serialize
Zip