The Wayback Machine - https://web.archive.org/web/20241127024309/https://www.geeksforgeeks.org/c-sharp-binary-writer/
Open In App

C# Binary Writer

Last Updated : 04 Aug, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Pre-requisites: Introduction to C#

C# is a general-purpose, modern and object-oriented programming language pronounced as “C Sharp”. It was developed by Microsoft led by Anders Hejlsberg. In C# Binary Writer is a class that is used to write primitive types as binary data in particular encoding stream. It is present under the System.IO namespace.

public class BinaryWriter : IAsyncDisposable, IDisposable
Binary writer class implements
 IAsyncDisposable and IDisposable interface

Syntax: 

initialize an instance of binary writer class

BinaryWriter bw = new BinaryWriter()

Initializes an instance of the BinaryWriter class based on the specified stream and using UTF-8 encoding.

BinaryWriter bw = new BinaryWriter(stream)

This will take a specified stream and any character encoding according to need.

BinaryWriter bw = new BinaryWriter(stream,encoding)

This will take a specified stream, character encoding, and an optional boolean value. If the boolean value is true then it will leave the output stream open after the disposal of the BinaryWriter object.

BinaryWriter bw = new BinaryWriter(stream,encoding,true)
S.No.

Method

Description

1

Write(Boolean)

Writes a one-byte boolean value 

2

Write(Byte)

Writes an unsigned byte to the current stream and advances 

the stream position by one byte

3

Write(Char)

Writes an Unicode character to the current stream and advances the

current position of the stream according to the Encoding

used and the character that has been written.

4

Write(Double)

Writes an eight-byte floating-point value to the current stream and 

advances the stream position by eight bytes.

5

Write(Int32)

Writes a four-byte unsigned integer to the current stream and 

advances the stream position by four bytes.

6

Write(String)

Writes a particular string to the current stream and advances the

current position of the stream according to the Encoding

used and the characters that have been there in string.

Example:

C#




// C# program for binary writer
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace binary_writer
{
    internal class Program
    {
        static void Main(string[] args)
        {
            using (BinaryWriter bw = new BinaryWriter(File.Open(
              @"C:\test\test.txt", FileMode.Create)))
            {
                //writes the data to the stream
                bw.Write(25);
                bw.Write(23.98);
                bw.Write('c');
                bw.Write("GeeksForGeeks");
                bw.Write(true);
                Console.WriteLine("Successfully Written");
                Console.ReadLine();
            }
        }
    }
}


Output:

Successfully Written

Now we see how to retrieve the data from the file.

Example 2: 

C#




// C# program for how to retrieve
// the data from the file:
 
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace binary_writer
{
    internal class Program
    {
        static void Main(string[] args)
        {
            using (BinaryReader bw = new BinaryReader
                   (File.Open(@"C:\test\test.txt", FileMode.Open)))
            {
                //Reads the data to the stream
                Console.WriteLine("String value is " + bw.ReadInt32());
                Console.WriteLine("Double value is " + bw.ReadDouble());
                Console.WriteLine("Char value is " + bw.ReadChar());
                Console.WriteLine("value of string is " + bw.ReadString());
                Console.WriteLine("for boolean value is " + bw.ReadBoolean());
                Console.Read();
                
            }
        }
    }
}


Output:

 



Previous Article
Next Article

Similar Reads

Binary Literals and Digit Separators in C#
Binary Literals The fixed values are called as Literal. Literal is a value which is used by the variables. Before C# 7.0 six types of literals are available that are an integer, Floating-point, Character, String, Null, Boolean literals. In C# 7.0 there is one more literal is added which is known as Binary Literal. The binary literal is used to stor
2 min read
C# Program to Find Binary Equivalent of an Integer using Recursion
Given an integer number, now we convert the given integer number into a binary number using recursion. Recursion is a method in which a function calls itself directly or indirectly and such type of function is known as a recursive function. It solves the problem very efficiently like we find the binary equivalent of an integer. Examples: Input : 10
3 min read
Implementing Binary Reader Using C#
BinaryReader is a class that is present under the System.IO namespace. This is used for handling the binary values from a particular encoding stream. Syntax: This will create the BinaryReader object for a particular input stream by using UTF-8 encoding. BinaryReader br = new BinaryReader(Stream) This will take a particular input stream and can pass
2 min read
C# Tutorial
In this C# (C Sharp) tutorial, whether you’re beginner or have experience with other programming languages, our free C# tutorials covers the basic and advanced concepts of C# including fundamentals of C#, including syntax, data types, control structures, classes, and objects. You will also dive into more advanced topics like exception handling, and
8 min read
ASP.NET Interview Questions and Answer
ASP.NET is a popular framework by Microsoft for building fast and scalable web applications. It allows developers to create dynamic websites, services, and apps, using server-side code and offering a user-friendly experience. Trusted by companies like Microsoft, Dell, and Accenture, ASP.NET is used to build many enterprise-level applications and we
15+ min read
C# Interview Questions and Answers
C# is the most popular general-purpose programming language and was developed by Microsoft in 2000, renowned for its robustness, flexibility, and extensive application range. It is simple and has an object-oriented programming concept that can be used for creating different types of applications. Here, we will provide 50+ C# Interview Questions and
15+ min read
Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework
Prerequisites: Download and Install Microsoft SQL Server Management StudioDownload and Setting Up Visual Studio Community Version MVC stands for Model View Controller. It is a design pattern that is employed to separate the business logic, presentation logic, and data. Basically, it provides a pattern to style web application. As per MVC, you can d
6 min read
Program to calculate Electricity Bill
Given an integer U denoting the amount of KWh units of electricity consumed, the task is to calculate the electricity bill with the help of the below charges: 1 to 100 units - [Tex]Rs. 10/unit[/Tex]100 to 200 units - [Tex]Rs. 15/unit[/Tex]200 to 300 units - [Tex]Rs. 20/unit[/Tex]above 300 units - [Tex]Rs. 25/unit[/Tex] Examples: Input: U = 250 Outp
9 min read
Lambda Expressions in C#
Lambda expressions in C# are used like anonymous functions, with the difference that in Lambda expressions you don't need to specify the type of the value that you input thus making it more flexible to use. The '=>' is the lambda operator which is used in all lambda expressions. The Lambda expression is divided into two parts, the left side is t
3 min read
Introduction to ASP.NET
ASP.NET is a web application framework designed and developed by Microsoft. ASP.NET is open source and a subset of the .NET Framework and successor of the classic ASP(Active Server Pages). With version 1.0 of the .NET Framework, it was first released in January 2002. So a question comes to mind that which technology we were using before the year 20
5 min read
HashSet in C# with Examples
In C#, HashSet is an unordered collection of unique elements. This collection is introduced in .NET 3.5. It supports the implementation of sets and uses the hash table for storage. This collection is of the generic type collection and it is defined under System.Collections.Generic namespace. It is generally used when we want to prevent duplicate el
6 min read
C# Dictionary with examples
In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.Collections.Generic namespace. It is dynamic in nature means the size of the dictionary is growing
5 min read
Map Reduce in Hadoop
One of the three components of Hadoop is Map Reduce. The first component of Hadoop that is, Hadoop Distributed File System (HDFS) is responsible for storing the file. The second component that is, Map Reduce is responsible for processing the file. MapReduce has mainly 2 tasks which are divided phase-wise.In first phase, Map is utilised and in next
9 min read
C# Multithreading
C# is a multi-paradigm programming language that supports several programming styles, including procedural, object-oriented, and functional programming. One of the essential features of C# is its support for multithreading, which enables developers to write applications that can perform multiple tasks concurrently. To create a new thread in C#, you
8 min read
Difference between Abstract Class and Interface in C#
An abstract class is a way to achieve abstraction in C#. To declare an abstract class, we use the abstract keyword. An Abstract class is never intended to be instantiated directly. This class must contain at least one abstract method, which is marked by the keyword or modifier abstract in the class definition. The Abstract classes are typically use
4 min read
C# | Arrays of Strings
An array is a collection of the same type variable. Whereas a string is a sequence of Unicode characters or array of characters. Therefore arrays of strings is an array of arrays of characters. Here, string array and arrays of strings both are same term. For Example, if you want to store the name of students of a class then you can use the arrays o
4 min read
C++ vs C#
C# is a general-purpose, modern, and object-oriented programming language pronounced as “C sharp”. It was developed by Microsoft led by Anders Hejlsberg and his team. C++ is a statically typed, multiparadigm, and object-oriented programming language. In the beginning, C++ was termed as C with classes. It was developed by Bjarne Stroustrup at AT
3 min read
Introduction to .NET Framework
The .NET Framework is a software development framework developed by Microsoft that provides a runtime environment and a set of libraries and tools for building and running applications on Windows operating systems. The framework includes a variety of programming languages, such as C#, F#, and Visual Basic, and supports a range of application types,
7 min read
Common Language Runtime (CLR) in C#
The Common Language Runtime (CLR) is a component of the Microsoft .NET Framework that manages the execution of .NET applications. It is responsible for loading and executing the code written in various .NET programming languages, including C#, VB.NET, F#, and others. When a C# program is compiled, the resulting executable code is in an intermediate
6 min read
C# | List Class
List<T> class represents the list of objects which can be accessed by index. It comes under the System.Collections.Generic namespace. List class can be used to create a collection of different types like integers, strings etc. List<T> class also provides the methods to search, sort, and manipulate lists. Characteristics: It is different
6 min read
C# | Encapsulation
Encapsulation is defined as the wrapping up of data and information under a single unit. It is the mechanism that binds together the data and the functions that manipulate them. In a different way, encapsulation is a protective shield that prevents the data from being accessed by the code outside this shield. Technically in encapsulation, the varia
5 min read
C# | Method Overriding
Method Overriding in C# is similar to the virtual function in C++. Method Overriding is a technique that allows the invoking of functions from another class (base class) in the derived class. Creating a method in the derived class with the same signature as a method in the base class is called as method overriding. In simple words, Overriding is a
8 min read
C# | Jagged Arrays
Prerequisite: Arrays in C#Jagged array is a array of arrays such that member arrays can be of different sizes. In other words, the length of each array index can differ. The elements of Jagged Array are reference types and initialized to null by default. Jagged Array can also be mixed with multidimensional arrays. Here, the number of rows will be f
5 min read
C# | Delegates
A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. Delegates in C# are similar to the function pointer in C/C++. It provides a way which tells which method is to be called when an event is triggered. For example, if you click on a Button on a form (Windows Form a
6 min read
C# | Inheritance
Introduction: Inheritance is a fundamental concept in object-oriented programming that allows us to define a new class based on an existing class. The new class inherits the properties and methods of the existing class and can also add new properties and methods of its own. Inheritance promotes code reuse, simplifies code maintenance, and improves
7 min read
C# | Substring() Method
In C#, Substring() is a string method. It is used to retrieve a substring from the current instance of the string. This method can be overloaded by passing the different number of parameters to it as follows: String.Substring(Int32) Method String.Substring(Int32, Int32) Method String.Substring Method (startIndex) This method is used to retrieves a
3 min read
C# | Arrays
An array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float, etc. and the elements are stored in a contiguous location. Length of the array specifies the number of elements present in the array
13 min read
C# | Operators
Operators are the foundation of any programming language. Thus the functionality of C# language is incomplete without the use of operators. Operators allow us to perform different kinds of operations on operands. In C#, operators Can be categorized based upon their different functionality : Arithmetic OperatorsRelational OperatorsLogical OperatorsB
15 min read
C# | Data Types
Data types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C#, each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given program must be described with one of the data type
7 min read
C# Decision Making (if, if-else, if-else-if ladder, nested if, switch, nested switch)
Decision Making in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of program based on certain conditions. These are used to cause the flow of execution to advance
5 min read
Article Tags :
three90RightbarBannerImg