Breaking News

Thursday 26 September 2013

c# File IO using Reading from and Writing into Binary Files

The BinaryReader and BinaryWriter classes are used for reading from and writing to s binary file.

The BinaryReader class:

The BinaryReader classes is used to read Binary data from a file. A BinaryReader object is created by passing a FileStream Object to its constructor.

some of the commonly used method of BinaryReader class :


  • Close()  >> it closes the BinaryReader object and the underlying stream.
  • Read()  >> read the character from the underlying stream.
  • ReadBoolean()  >> reads a boolean value from current stream and advances current the position of the stream.
  • ReadByte()  >> reads the next bytes from the current stream.
  • ReadChar() >> reads the next character from the current stream.
  • ReadDouble() >> reads an floating points value from the current stream.
  • ReadString() >> reads a string from a current stream.
The BinaryWriter Class:

The BinaryWriter class is used to Write data to a stream. A BinaryWriter object is created by passing a FileStream object to its constructor.

some of the commonly used method of BinaryWriter class :

  • Close()  >> its close the BinaryWriter class object and underlying stream.
  • Flush()   >> clear all buffer for the current writer.
  • Seek(int offset , SeekOrigin Origin)  >> sets the position within the current stream.
  •  Write(bool value)  >> write a one-byte boolean value to the current stream.
  • Write(byte value)  >> write an unsigned byte to the current stream.
  • Write(byte[] buffer)  >> writes a byte array to the underlying stream.
  • Write(string value)  >> reads a string value from the current stream.

Example:


using System.IO;

namespace binaryreader_and_binarywriter_classes.cs
{
    public class RWDATA
    {
        static void Main(string[] args)
        {
            int i = 10;
            double d = 1023.23;
            bool b = true;

            FileStream fs = new FileStream("C://USING IO/testdata",FileMode.Create);
            BinaryWriter dataout = new BinaryWriter(fs);
            Console.WriteLine("writing"+i);
            dataout.Write(i);
            Console.WriteLine("writing"+b);
            dataout.Write(b);
            Console.WriteLine("writing"+d);
            dataout.Write(1023.23);
            dataout.Close();
            Console.WriteLine("");
            // now read them back
            FileStream fs1 = new FileStream("C://USING IO/testdata", FileMode.Open);
            BinaryReader datain = new BinaryReader(fs1);
            i = datain.ReadInt32();
            Console.WriteLine("reading "+ i);
            b = datain.ReadBoolean();
            Console.WriteLine("reading "+ b);
            d = datain.ReadDouble();
            Console.WriteLine("reading "+1023.23);
            Console.ReadLine();
            datain.Close();
        }
    }
}


output :




Reference Link :




No comments:

Post a Comment

© 2013 Post by repter_x