illustrates use of MemoryStreams : File MemoryStream « File Stream « C# / C Sharp






illustrates use of MemoryStreams

 
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy

Publisher: Sybex;
ISBN: 0782129110
*/



 /*
  Example15_13.cs illustrates use of MemoryStreams
*/

using System;
using System.Windows.Forms;
using System.IO;

public class Example15_13 
{

  // SaveMemoryStream saves the MemoryStream as a file
  public static void SaveMemoryStream(
    MemoryStream ms, string FileName)
  {
    FileStream outStream = File.OpenWrite(FileName);
    ms.WriteTo(outStream);
    outStream.Flush();
    outStream.Close();
  }

    [STAThread]
  public static void Main() 
  {

    // use an open file dialog to get a filename
    OpenFileDialog dlgOpen = new OpenFileDialog();
    dlgOpen.Title="Select file to back up";

    if (dlgOpen.ShowDialog() == DialogResult.OK)
    {
      // Read the file into a MemoryStream
      FileStream inStream = File.OpenRead(dlgOpen.FileName);
      MemoryStream storeStream = new MemoryStream();

      // copy all data from in to store
      storeStream.SetLength(inStream.Length);
      inStream.Read(storeStream.GetBuffer(), 0, (int)inStream.Length);

      // clean up
      storeStream.Flush();
      inStream.Close();

      // pass the store to a method to write it out
      SaveMemoryStream(storeStream, dlgOpen.FileName + ".bak");
      storeStream.Close();

    }

  }

}

           
         
  








Related examples in the same category

1.Demonstrate MemoryStreamDemonstrate MemoryStream
2.Demonstrates reading a file into memory, attaching it to a MemoryStream and using stream methods to access the contents
3.Copy a object by content,not by reference