illustrates use of BufferedStreams

   

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

Publisher: Sybex;
ISBN: 0782129110
*/

 /*
  Example15_14.cs illustrates use of BufferedStreams
*/

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

public class Example15_14 
{
    [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)
    {
      // create the raw streams
      FileStream inStream = File.OpenRead(dlgOpen.FileName);
      FileStream outStream = 
        File.OpenWrite(dlgOpen.FileName + ".bak");

      // add a buffering layer
      BufferedStream bufInStream = new BufferedStream(inStream);
      BufferedStream bufOutStream = new BufferedStream(outStream);

      byte[] buf = new byte[4096];
      int bytesRead;

      // copy all data from in to out via the buffer layer
      while ((bytesRead = bufInStream.Read(buf, 0, 4096)) > 0)
        bufOutStream.Write(buf, 0, bytesRead);

      // clean up
      bufOutStream.Flush();
      bufOutStream.Close();
      bufInStream.Close();
      outStream.Close();
      inStream.Close();

    }

  }

}



           
          


Create a FileStream for the BufferedStream.

using System;
using System.IO;

class BufStreamApp
{
static void Main(string[] args)
{
FileStream fs = new FileStream(“Hoo.txt”,FileMode.Create, FileAccess.ReadWrite);
BufferedStream bs = new BufferedStream(fs);
Console.WriteLine(“Length: {0} Position: {1}”,bs.Length, bs.Position);

for (int i = 0; i < 64; i++) { bs.WriteByte((byte)i); } Console.WriteLine("Length: {0} Position: {1}", bs.Length, bs.Position); byte[] ba = new byte[bs.Length]; bs.Position = 0; bs.Read(ba, 0, (int)bs.Length); foreach (byte b in ba) { Console.Write("{0,-3}", b); } string s = "Foo"; for (int i = 0; i < 3; i++) { bs.WriteByte((byte)s[i]); } Console.WriteLine(" Length: {0} Position: {1} ",bs.Length, bs.Position); for (int i = 0; i < (256-67)+1; i++) { bs.WriteByte((byte)i); } Console.WriteLine(" Length: {0} Position: {1} ", bs.Length, bs.Position); bs.Close(); } } [/csharp]

BitConvert in action


   


using System;
using System.IO;
using System.Text;

class Test
{
    public static void Main() 
    {        
        using (StreamWriter output = new StreamWriter("practice.txt")) 
        {
            // Create and write a string containing the symbol for Pi.
            string srcString = "Area = u03A0r^2";

            // Convert the UTF-16 encoded source string to UTF-8 and ASCII.
            byte[] utf8String = Encoding.UTF8.GetBytes(srcString);
            byte[] asciiString = Encoding.ASCII.GetBytes(srcString);
            
            // Write the UTF-8 and ASCII encoded byte arrays. 
            output.WriteLine("UTF-8  Bytes: {0}", BitConverter.ToString(utf8String));
            output.WriteLine("ASCII  Bytes: {0}", BitConverter.ToString(asciiString));
            
            Console.WriteLine(BitConverter.ToString(utf8String));
            Console.WriteLine(BitConverter.ToString(asciiString));
        }
    }
}
           
          


Use BitConvert to convert String, Boolean and Int32


   


using System;
using System.IO;

class Test {
    public static void Main() {
        byte[] b = BitConverter.GetBytes(true);
        Console.WriteLine(BitConverter.ToString(b));
        Console.WriteLine(BitConverter.ToBoolean(b,0));
        b = BitConverter.GetBytes(3678);
        Console.WriteLine(BitConverter.ToString(b));

        // Convert a byte array to an int and display.
        Console.WriteLine(BitConverter.ToInt32(b,0));
    }
}

           
          


Read and Write a Binary File

   
 

using System;
using System.IO;

public class BinaryFileTest {

    private static void Main() {
        FileStream fs = new FileStream("test.dat", FileMode.Create);
        BinaryWriter w = new BinaryWriter(fs);

        w.Write(1.2M);
        w.Write("string");
        w.Write("string 2");
        w.Write(&#039;!&#039;);
        w.Flush();
        w.Close();
        fs.Close();

        fs = new FileStream("test.dat", FileMode.Open);
        StreamReader sr = new StreamReader(fs);
        Console.WriteLine(sr.ReadToEnd());
        fs.Position = 0;
        BinaryReader br = new BinaryReader(fs);
        Console.WriteLine(br.ReadDecimal());
        Console.WriteLine(br.ReadString());
        Console.WriteLine(br.ReadString());
        Console.WriteLine(br.ReadChar());
        fs.Close();

    }
}

    


Read the data from a file and desiralize it

   

/*
 * 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;
using System.Runtime.Serialization.Formatters.Binary;

namespace Client.Chapter_11___File_and_Streams
{
  public class Class1Chapter_11___File_and_Streams {
    [STAThread]
    static void Main(string[] args)
    {
      Point p1 = new Point();

      p1.xpoint = 0x1111;
      p1.ypoint = 0x2222;

      // Opens a file and serializes the object into it.
      Stream stream = File.Open("onepoint.bin", FileMode.Create);
      BinaryFormatter bformatter = new BinaryFormatter();

      bformatter.Serialize(stream, p1);
      stream.Close();

      //Read the data from a file and desiralize it
      Stream openStream = File.Open("onepoint.bin", FileMode.Open);
      Point desierializedPoint = new Point();

      desierializedPoint = (Point)bformatter.Deserialize(openStream);
    }
  }
  [Serializable()]
  class Point
  {
    public int xpoint;
    public int ypoint;
  }

}

           
          


File pointer move and read binary file

   


using System;
using System.IO;
using System.Text;

class Class1{
  static void Main(string[] args)  {
         byte[] byData = new byte[100];
         char[] charData = new Char[100];

         try {
            FileStream aFile = new FileStream("practice.txt",FileMode.Open);
            aFile.Seek(55,SeekOrigin.Begin);
            aFile.Read(byData,0,100);
         }
         catch(IOException e)
         {
            Console.WriteLine("An IO exception has been thrown!");
            Console.WriteLine(e.ToString());
            Console.ReadLine();
            return;
         }

         Decoder d = Encoding.UTF8.GetDecoder();
         d.GetChars(byData, 0, byData.Length, charData, 0);

         Console.WriteLine(charData);
         return;
  }
}