Saturday, 28 May 2016

binarywriter

Create binary file.
It’s used to write primitive data in binary format.
You can use parameter constructor of binary writer to create binary file.
List of parameter constructor in Binary Writer:
Namespace required to use binarywriter is System.IO


public BinaryWriter(Stream output);
Stream: output is the name of the output stream.

public BinaryWriter(Stream output, Encoding encoding);
Encoding: is the character encoding to use. Encoding is available in System.Text namespace.  Encoding is an abstract class. It is used to various text formats.

public BinaryWriter(Stream output, Encoding encoding, bool leaveOpen);
leaveOpen: True to leave the stream open after the BinaryReader object is disposed; otherwise, false.
Let’s take an example of BinaryWriter:

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

class Program
{
    static void Main()
    {
        try
        {
            int[] intArray = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            using(BinaryWriter bw = new BinaryWriter(File.Open("test.txt",FileMode.OpenOrCreate)))
            {
                foreach(int a in intArray)
                {
                    bw.Write(a);
                }
            }
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message.ToString());
        }
    }
}
Now you can check file “test.txt” in bin directory of the program.
In this file binary data stored. If you want to read those data from original format you can use BinaryReader.

List of methods in BinaryWriter:
Write: Uint64, Uint32, Uint16, string, single, sByte, Int64, Int32, Int16, Double, Decimal, Char[], char, Byte, Byte[], Boolean to write in binary file with respective datatypes.
Dispose: release all resource used by the current instance of binarywriter.
Close: close the current reader and underlying stream.
Seek: Set the position within the current stream.
Flush: Clear all buffers for the current writer and causes any buffered data to be written to underlying device.
Finalize: Allows an object to try to free resource and perform other cleanup operation before it is reclaimed by garbage collection.


you can also visit:  www.mybook-lang.com

No comments:

Post a Comment