Example 1: demonstrates the use of BinaryReader and BinaryWriter classes. The example makes use of FileStream class. A detailed explanation of the FileStream will follow.
using System;
using System.IO;
namespace Session13Example1
{
///
/// Summary description for Class1.
///
class BinaryDemo
{
private const string filename = "Binary.data";
///
/// The main entry point for the application.
///
[STAThread]
public static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
//Check if file already exists
if(File.Exists(filename))
{
Console.WriteLine("{0} already exists!", filename);
return;
}
//If not exist then create a new empty data file.
FileStream fs = new FileStream(filename, FileMode.CreateNew);
//Create the writer for data.
BinaryWriter w = new BinaryWriter(fs);
for(int i=0; i<11; i++)
{
w.Write((int) i);
}
Console.WriteLine("Data has been written to the file!");
w.Close();
fs.Close();
//Create the reader for data.
fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
Console.WriteLine("The Data file contents are:");
//Read data from the data file.
for(int i=0; i<11; i++)
{
Console.WriteLine(r.ReadInt32());
}
w.Close();
}
}
}
...To be continued
No comments:
Post a Comment