illustrates reading and writing binary data

image_pdfimage_print


   

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

Publisher: Sybex;
ISBN: 0782129110
*/


 /*
  Example15_15.cs illustrates reading and writing binary data
*/

using System;
using System.IO;

public class Example15_15 
{

  public static void Main() 
  {

    // create a new file to work with
    FileStream outStream = File.Create("c:BinaryTest.dat");

    // use a BinaryWriter to write formatted data to the file
    BinaryWriter bw = new BinaryWriter(outStream);

    // write various data to the file
    bw.Write( (int) 32);
    bw.Write( (decimal) 4.567);
    string s = "Test String";
    bw.Write(s);

    // flush and close
    bw.Flush();
    bw.Close();

    // now open the file for reading
    FileStream inStream = File.OpenRead("c:BinaryTest.dat");

    // use a BinaryReader to read formatted data and dump it to the screen
    BinaryReader br = new BinaryReader(inStream);

    int i = br.ReadInt32();
    decimal d = br.ReadDecimal();
    string s2 = br.ReadString();

    Console.WriteLine(i);
    Console.WriteLine(d);
    Console.WriteLine(s2);

    // clean up
    br.Close();

  }

}


           
          


This entry was posted in File Stream. Bookmark the permalink.