C# binary file reading and writing


Release date:2023-09-02 Update date:2023-10-13 Editor:admin View counts:206

Label:

C# binary file reading and writing

BinaryReader and BinaryWriter class is used to read and write binary files.

BinaryReader class

BinaryReader class is used to read binary data from a file. One BinaryReader object created by passing to its constructor FileStream object.

The following table lists some BinaryReader commonly used methods:

Serial number

Method & description

1

Public override void Close () closes the BinaryReader object and the underlying stream.

2

Public virtual int Read () reads characters from the underlying stream and moves the current position of the stream forward.

3

Public virtual bool ReadBoolean () reads a Boolean value from the current stream and moves the current position of the stream forward one byte.

4

Public virtual byte ReadByte () reads the next byte from the current stream and moves the current position of the stream forward one byte.

5

Public virtual byte [] ReadBytes (int count) reads a specified number of bytes from the current stream into a byte array and moves the current position of the stream forward a specified number of bytes.

6

Public virtual char ReadChar () reads the next byte from the current stream and moves the current position of the stream forward according to the encoding used and the specified characters read from the stream.

7

Public virtual char [] ReadChars (int count) reads a specified number of bytes from the current stream, returns an array in a character array, and moves the current position of the stream forward according to the encoding used and the specified characters read from the stream.

8

Public virtual double ReadDouble () reads an 8-byte floating-point value from the current stream and moves the current position of the stream forwardeight bytes.

9

Public virtual int ReadInt32 () reads a 4-byte signed integer from the current stream and moves the current position of the stream forward four bytes.

10

Public virtual string ReadString () reads a string from the current stream. The string is prefixed with length and is encoded as a seven-digit integer.

For a complete list of methods, please visit Microsoft’s C # documentation.

BinaryWriter class

BinaryWriter class is used to write binary data to a file. One BinaryWriter object created by passing to its constructor FileStream object.

The following table lists some BinaryWriter commonly used methods:

Serial number

Method & description

1

Public override void Close () closes the BinaryWriter object and the underlying stream.

2

Public virtual void Flush () cleans up all buffers of the current writer so that all buffered data is written to the underlying device.

3

Public virtual long Seek (int offset, SeekOrigin origin) sets the location within the current stream.

4

Public virtual void Write (bool value) writes a single-byte Boolean value tothe current stream, and 0 represents false,1 for true.

5

Public virtual void Write (byte value) writes an unsigned byte to the current stream and moves the stream forward one byte.

6

Public virtual void Write (byte [] buffer) writes a byte array to the underlying stream.

7

Public virtual void Write (char ch) writes a Unicode character to the current stream and moves the current position of the stream forward according to the encoding used and the specified character to be written to the stream.

8

Public virtual void Write (char [] chars) writes an array of characters to the current stream and moves the current position of the stream forward according to the encoding used and the specified characters to be written tothe stream.

9

Public virtual void Write (double value) writes an 8-byte floating-point value to the current stream and moves the stream forward eight bytes.

10

Public virtual void Write (int value) writes a 4-byte signed integer to the current stream and moves the stream forward four bytes.

11

Public virtual void Write (string value) writes a string prefixed with length to the currently encoded stream of the BinaryWriter and moves the current position of the stream forward according to the encoding used and the specified characters to be written to the stream.

For a complete list of methods, please visit Microsoft’s C # documentation.

Example

The following example demonstrates reading and writing binary data:

Example

using System;
using System.IO;
namespace BinaryFileApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            BinaryWriter bw;
            BinaryReader br;
            int i = 25;
            double d = 3.14157;
            bool b = true;
            string s = "I am happy";
            // create a file
            try
            {
                bw = new BinaryWriter(new FileStream("mydata",
                                FileMode.Create));
            }
            catch (IOException e)
            {
                Console.WriteLine(e.Message + "\\n Cannot create
file.");
                return;
            }
            // write file
            try
            {
                bw.Write(i);
                bw.Write(d);
                bw.Write(b);
                bw.Write(s);
            }
            catch (IOException e)
            {
                Console.WriteLine(e.Message + "\\n Cannot write to
file.");
                return;
            }
            bw.Close();
            // read file
            try
            {
                br = new BinaryReader(new FileStream("mydata",
                                FileMode.Open));
            }
            catch (IOException e)
            {
                Console.WriteLine(e.Message + "\\n Cannot open file.");
                return;
            }
            try
            {
                i = br.ReadInt32();
                Console.WriteLine("Integer data: {0}", i);
                d = br.ReadDouble();
                Console.WriteLine("Double data: {0}", d);
                b = br.ReadBoolean();
                Console.WriteLine("Boolean data: {0}", b);
                s = br.ReadString();
                Console.WriteLine("String data: {0}", s);
            }
            catch (IOException e)
            {
                Console.WriteLine(e.Message + "\\n Cannot read from
file.");
                return;
            }
            br.Close();
            Console.ReadKey();
        }
    }
}

When the above code is compiled and executed, it produces the following results:

Integer data: 25
Double data: 3.14157
Boolean data: True
String data: I am happy

Powered by TorCMS (https://github.com/bukun/TorCMS).