Writes the same string to a file and to the screen using a common method


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

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// WriteOut.cs -- Writes the same string to a file and to the screen using
//                a common method.
//
//                Compile this program with the following command line:
//                    C:>csc WriteOut.cs
namespace nsStreams
{
    using System;
    // When using streams, you must declare that you are using System.IO
    using System.IO;
    
    public class WriteOut
    {
        static public void Main ()
        {
            string str = "This is a line of text
";
            
            // Open the standard output stream
            Stream ostrm = Console.OpenStandardOutput ();
            
            // Open a file. You should protect an open in a try ... catch block
            FileStream fstrm;
            try
            {
                fstrm = new FileStream ("./OutFile.txt", FileMode.OpenOrCreate);
            }
            catch
            {
                Console.WriteLine ("Failed to open file");
                return;
            }
            
            // Call WriteToStream() to write the same string to both
            WriteToStream (ostrm, str);
            WriteToStream (fstrm, str);
            
            // Close the file.
            fstrm.Close ();
            ostrm.Close ();
        }
        static public void WriteToStream (Stream strm, string text)
        {
            foreach (char ch in text)
            {
                strm.WriteByte ((Byte) ch);
            }
            // Flush the output to make it write
            strm.Flush ();
        }
    }
}



           
         
     


Demonstrates opening/creating a file for writing and truncating its length to 0 bytes.

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

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// StrmWrit.cs — Demonstrates opening/creating a file for writing and truncating
// its length to 0 bytes.
// Compile this program with the following command line:
// C:>csc StrmWrit.cs
using System;
using System.IO;

namespace nsStreams
{
public class StrmWrit
{
static public void Main ()
{
FileStream strm;
// Open or create the file for writing
try
{
strm = new FileStream (“./write.txt”, FileMode.OpenOrCreate, FileAccess.Write);
}
// If the open fails, the constructor will throw an exception.
catch (Exception e)
{
Console.WriteLine (e.Message);
Console.WriteLine (“Cannot open write.txt for writing”);
return;
}
// Truncate the file using the SetLength() method.
strm.SetLength (0);
Console.WriteLine (“Enter text. Type a blank line to exit
“);
// Accept text from the keyboard and write it to the file.
while (true)
{
string str = Console.ReadLine ();
if (str.Length == 0)
break;
byte [] b; // = new byte [str.Length];
StringToByte (str, out b);
strm.Write (b, 0, b.Length);
}
Console.WriteLine (“Text written to write.txt”);
// Close the stream
strm.Close ();
}
//
// Convert a string to a byte array, adding a carriage return/line feed to it
static protected void StringToByte (string str, out byte [] b)
{
b = new byte [str.Length + 2];
int x;
for (x = 0; x < str.Length; ++x) { b[x] = (byte) str[x]; } // Add a carriage return/line feed b[x] = 13; b[x + 1] = 10; } } } [/csharp]

Demonstrates seeking to a position in a file from the end


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

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/

// Seek.cs -- Demonstrates seeking to a position in a file from the end,
//            middle and beginning of a file
//
//            Compile this program with the following command line:
//                C:>csc Seek.cs
using System;
using System.IO;
using System.Text;

namespace nsStreams
{
    public class Seek
    {
        const string str1 = "Now is the time for all good men to " +
                            "come to the aid of their Teletype.
";
        const string str2 = "The quick red fox jumps over the " +
                           "lazy brown dog.
";
        static public void Main ()
        {
            FileStream strm;
            try
            {
                strm = new FileStream ("./StrmSeek.txt",
                                       FileMode.Create,
                                       FileAccess.ReadWrite);
            }
            catch (Exception e)
            {
                Console.WriteLine (e);
                Console.WriteLine ("Cannot open StrmSeek.txt " +
                                   "for reading and writing");
                return;
            }
// Clear out any remnants in the file
//            strm.SetLength (0);
            foreach (char ch in str1)
            {
                strm.WriteByte ((byte) ch);
            }
            foreach (char ch in str2)
            {
                strm.WriteByte ((byte) ch);
            }
// Seek from the beginning of the file
            strm.Seek (str1.Length, SeekOrigin.Begin);
// Read 17 bytes and write to the console.
            byte [] text = new byte [17];
            strm.Read (text, 0, text.Length);
            ShowText (text);
// Seek back 17 bytes and reread.
            strm.Seek (-17, SeekOrigin.Current);
            strm.Read (text, 0, text.Length);
            ShowText (text);
// Seek from the end of the file to the beginning of the second line.
            strm.Seek (-str2.Length, SeekOrigin.End);
            strm.Read (text, 0, text.Length);
            ShowText (text);
        }
        static void ShowText (byte [] text)
        {
            StringBuilder str = new StringBuilder (text.Length);
            foreach (byte b in text)
            {
    
                str.Append ((char) b);
            }
            Console.WriteLine (str);
        }
    }
}
//File: StrmSeek.txt

/*
Now is the time for all good men to come to the aid of their Teletype.
The quick red fox jumps over the lazy brown dog.

*/

           
         
     


Copy a object by content,not by reference

   
 

//http://tinyerp.codeplex.com/
//GNU Library General Public License (LGPL)
//-----------------------------------------------------------------------
// <copyright file="SysUtil.cs" company="Pyramid Consulting">
//     Copyright (c) Pyramid Consulting. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;

namespace Bamboo.Core.Common
{
    public class SysUtil
    {

        /// <summary>
        /// copy a object by content,not by reference
        /// </summary>
        /// <typeparam name="T">type of object</typeparam>
        /// <param name="srcObject">source objected to be cloned</param>
        /// <returns>the object that cloned from the source object</returns>
        public static T SerializeClone<T>(T srcObject)
        {
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bfFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            System.IO.MemoryStream msStream = new System.IO.MemoryStream();
            T result = default(T);
            try
            {
                bfFormatter.Serialize(msStream, srcObject);
                msStream.Seek(0, System.IO.SeekOrigin.Begin);
                result=(T)bfFormatter.Deserialize(msStream);
            }
            finally
            {
                if (msStream != null) msStream.Close();
            }
            return result;
        }
    }
}

   
     


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

/*
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

   
 
/*
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

/*
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]