Saturday 28 April 2012

Beginning .Net , C# Tips : Reading and writing binary data in C# Programming

Now use the BinaryReader and BinaryWriter classes to read and write primitive types to a file.The BinaryWriter writes primitive objects in their native format, so in order to read them using the BinaryReader, you must select the appropriate Read method.
The Example shows you how to do that; in this case, you are writing a value from a number of different primitive types to the text file and then reading the same value.

Here are sample Example :

C# Example :
        ///////Write to a file
        System.IO.BinaryWriter binarywriter =new System.IO.BinaryWriter(System.IO.File.Create(MapPath
 ("BinaryFile.dat")));
        binarywriter.Write("This is a sample string.");
        binarywriter.Write(0x12346789abcdef);
        binarywriter.Write(0x12345678);
        binarywriter.Write('c');
        binarywriter.Write(1.5f);
        binarywriter.Write(1000.2m);
        binarywriter.Close();

        ////////Read from a file
        System.IO.BinaryReader binaryreader = new System.IO.BinaryReader(System.IO.File.Open
(MapPath("BinaryFile.dat"), System.IO.FileMode.Open));
        string strA = binaryreader.ReadString();
        long lngL = binaryreader.ReadInt64();
        int intI = binaryreader.ReadInt32();
        char chrC = binaryreader.ReadChar();
        float fltF = binaryreader.ReadSingle();
        decimal dclD = binaryreader.ReadDecimal();
        binaryreader.Close();


If you open this file in Notepad, you will see that the BinaryWriter has written the nonreadable binary data to the file. The BinaryReader provides a number of different methods for reading various kinds of Primitive types from the stream. In this Example, you use a different Read method for each primitive type that you Write to the file.

VB.net Example :
    Dim binarywriter As New System.IO.BinaryWriter(System.IO.File.Create(MapPath("binary.dat")))
    binarywriter.Write("a string")
    binarywriter.Write(&H12346789ABCDEF)
    binarywriter.Write(&H12345678)
    binarywriter.Write("c"c)
    binarywriter.Write(1.5F)
    binarywriter.Write(100.2D)
    binarywriter.Close()

    Dim binaryreader As New System.IO.BinaryReader(System.IO.File.Open(MapPath
     ("binary.dat"),System.IO.FileMode.Open))
    Dim a As String = binaryreader.ReadString()
    Dim l As Long = binaryreader.ReadInt64()
    Dim i As Integer = binaryreader.ReadInt32()
    Dim c As Char = binaryreader.ReadChar()
    Dim f As Double = binaryreader.ReadSingle()
    Dim d As Decimal = binaryreader.ReadDecimal()
    binaryreader.Close()

No comments:

Post a Comment