Demonstrates reading a file into memory, attaching it to a MemoryStream and using stream methods to access the contents

image_pdfimage_print

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// MemStrm.cs — Demonstrates reading a file into memory, attaching it to a
// MemoryStream and using stream methods to access the contents
//
// Compile this program with the following command line:
// C:>csc MemStrm.cs
using System;
using System.IO;

namespace nsStreams
{
public class MemStrm
{
const string USA = “[USA]”;
const string PhoneEntry = “Phone_number=”;
static public void Main ()
{
FileStream cfg;
try
{
cfg = new FileStream (“./config.ini”,
FileMode.Open,
FileAccess.ReadWrite);
}
catch (FileNotFoundException)
{
Console.WriteLine (“Cannot find ./config.ini”);
return;
}
catch (Exception e)
{
Console.WriteLine (e.Message);
Console.WriteLine (“Cannot find ./config.ini”);
return;
}
MemoryStream mem = new MemoryStream ((int) cfg.Length);
cfg.Read (mem.GetBuffer(), 0, (int) cfg.Length);
int pos = FindInBuffer (USA, 0, mem.GetBuffer());
if (pos < 0) { Console.WriteLine ("Could not find match in buffer"); } else { pos = FindInBuffer (PhoneEntry, pos, mem.GetBuffer()); if (pos < 0) { Console.WriteLine ("Could not find phone number"); } else { const string NewPhone = "1888555-9876"; mem.Seek (pos + PhoneEntry.Length, SeekOrigin.Begin); for (int x = 0; x < NewPhone.Length; ++x) { mem.WriteByte ((byte) NewPhone[x]); } cfg.SetLength (0); cfg.Write (mem.GetBuffer(), 0, (int) mem.GetBuffer().Length); } } cfg.Flush (); cfg.Close (); mem.Close (); } // // Find a string of characters in a buffer of type byte static int FindInBuffer (string ToFind, int start, byte [] buf) { for (int x = start; x < buf.Length; ++x) { if (buf[x] == (byte) ToFind[0]) { int y; for (y = 1; y < ToFind.Length; ++y) { if ((x + y) >= buf.Length)
break;
if (buf[x + y] != (byte) ToFind[y])
break;
}
if (y == ToFind.Length)
{
return (x);
}
}
}
return (-1);
}
//
// Convert a buffer of type string to byte
static void StringToByte (out byte [] b, string str)
{
b = new byte [str.Length];
for (int x = 0; x < str.Length; ++x) { b[x] = (byte) str [x]; } } // // Convert a buffer of type byte to a string static string ByteToString (byte [] b, int start) { string str = ""; for (int x = start; x < b.Length; ++x) { str += (char) b [x]; } return (str); } } } //File: config.ini /* [PROGRAM] Program Directory=C:TEMP Data Directory= [DEFAULTS] Phone_number=800-555-2345 Wallpaper=wallppr.bmp sshow=default [Modem] Initialization String=ATX4L1 Dial Type=1 [Countries] 1=USA 2=Canada 3=United Kingdom [USA] Phone_number=1800555-1234 TOLLFREE=1 [Canada] Phone_number=1800555-2345 TOLLFREE=1 [United Kingdom] Phone_number=08009872345 TOLLFREE=1 */ [/csharp]

illustrates use of MemoryStreams

image_pdfimage_print
   
 
/*
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();

    }

  }

}

           
         
     


Demonstrate MemoryStream

image_pdfimage_print

/*
C#: The Complete Reference
by Herbert Schildt

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

// Demonstrate MemoryStream.

using System;
using System.IO;

public class MemStrDemo {
public static void Main() {
byte[] storage = new byte[255];

// Create a memory-based stream.
MemoryStream memstrm = new MemoryStream(storage);

// Wrap memstrm in a reader and a writer.
StreamWriter memwtr = new StreamWriter(memstrm);
StreamReader memrdr = new StreamReader(memstrm);

// Write to storage, through memwtr.
for(int i=0; i < 10; i++) memwtr.WriteLine("byte [" + i + "]: " + i); // put a period at the end memwtr.Write('.'); memwtr.Flush(); Console.WriteLine("Reading from storage directly: "); // Display contents of storage directly. foreach(char ch in storage) { if (ch == '.') break; Console.Write(ch); } Console.WriteLine(" Reading through memrdr: "); // Read from memstrm using the stream reader. memstrm.Seek(0, SeekOrigin.Begin); // reset file pointer string str = memrdr.ReadLine(); while(str != null) { str = memrdr.ReadLine(); if(str.CompareTo(".") == 0) break; Console.WriteLine(str); } } } [/csharp]

Convert from a URL to a FileInfo

image_pdfimage_print
   
 

#region License and Copyright
/* -------------------------------------------------------------------------
 * Dotnet Commons IO
 *
 *
 * This library is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU Lesser General Public License as published by 
 * the Free Software Foundation; either version 2.1 of the License, or 
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License 
 * for more details. 
 *
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this library; if not, write to the 
 * 
 * Free Software Foundation, Inc., 
 * 59 Temple Place, 
 * Suite 330, 
 * Boston, 
 * MA 02111-1307 
 * USA 
 * 
 * -------------------------------------------------------------------------
 */
#endregion

using System;
using System.Collections;
using System.Globalization;
using System.IO;

namespace Dotnet.Commons.IO
{
  
  ///  
  /// <summary>  
  /// This class provides basic facilities for manipulating files and file paths.
    /// 
    /// <h3>File-related methods</h3>
    /// There are methods to 
    /// <list type="bullet">
    ///     <item>copy a file to another file,</item>
    ///     <item>compare the content of 2 files,</item>
    ///     <item>delete files using the wildcard character,</item>
    ///     <item>etc</item>
    /// </list>
  /// </summary>
  ///     
  public sealed class FileUtils
  {
        /// ---------------------------------------------------------------
        /// <summary> Convert from a <i>URL</i> to a <see cref="FileInfo"/>.</summary>
        /// <param name="url">File URL.
        /// </param>
        /// <returns> The equivalent <see cref="FileInfo"/> object, or <i>null</i> if the URL&#039;s protocol
        /// is not <i>file</i>
        /// </returns>
        /// ---------------------------------------------------------------
        public static FileInfo ToFileFromUri(System.Uri url)
        {
            if (url.Scheme.Equals("file") == false)
            {
                return null;
            }
            else
            {
                String filename = url.PathAndQuery.Replace(&#039;/&#039;, Path.DirectorySeparatorChar);
                return new FileInfo(filename);
            }
        }
    }
}

   
     


Open Existing File

image_pdfimage_print
   
 
/*
 * C# Programmers Pocket Consultant
 * Author: Gregory S. MacBeth
 * Email: gmacbeth@comporium.net
 * Create Date: June 27, 2003
 * Last Modified Date:
 * Version: 1
 */
using System;
using System.IO;

namespace Client.Chapter_11___File_and_Streams
{
  public class OpenExistingFile {
    static void Main(string[] args)
    {
      FileInfo MyFile = new FileInfo(@"c:ProjectsTesting.txt");
      FileStream MyStream;

      MyStream = MyFile.Open(FileMode.Open, FileAccess.Read, FileShare.None);
    }
  }
}

           
         
     


Creating Files

image_pdfimage_print
   
 
/*
 * C# Programmers Pocket Consultant
 * Author: Gregory S. MacBeth
 * Email: gmacbeth@comporium.net
 * Create Date: June 27, 2003
 * Last Modified Date:
 * Version: 1
 */

using System;
using System.IO;

namespace Client.Chapter_11___File_and_Streams
{
  public class CreatingFiles {
    public CreatingFiles()
    {
      FileInfo MyFile = new FileInfo(@"c:ProjectsTesting.txt");

      MyFile.Create();
    }
  }
}

           
         
     


Copying A File

image_pdfimage_print
   
 
/*
 * C# Programmers Pocket Consultant
 * Author: Gregory S. MacBeth
 * Email: gmacbeth@comporium.net
 * Create Date: June 27, 2003
 * Last Modified Date:
 * Version: 1
 */
using System;
using System.IO;

namespace Client.Chapter_11___File_and_Streams
{
  public class CopyingAFile {
    static void Main(string[] args)
    {
      FileInfo MyFile = new FileInfo(@"c:ProjectsTesting.txt");

      MyFile.Create();
      MyFile.CopyTo(@"c:ProjectsMyFolderMoved Testing.txt");

      //or
      MyFile.CopyTo(@"c:ProjectsMyFolderMoved Testing.txt", true);
    }
  }
}