The Wayback Machine - https://web.archive.org/web/20241127033418/https://www.geeksforgeeks.org/how-to-use-c-sharp-binarywriter-class/
Open In App

How to Use C# BinaryWriter Class?

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

In this article, we will illustrate a binary writer in C#. Following are some important points regarding Binary Writer:

  • Binary Writer is used to generating binary files.
  • Strings can be written in specific encoding using Binary Writer.
  • Binary Writer constructor takes an object of type Stream to create an object for the Binary Writer class.
  • The encoding is not specified and remains UTF-8 by default.

Syntax:

The syntax to create a Binary Writer object using constructors is given below:

protected BinaryWriter();

The below statement computes a new instance of the Binary Writer class and by default, it uses UTF-8 character encoding.

BinaryWriter binaryWriter = new BinaryWriter(outputStream) ;

The below statement computes a new instance of the Binary Writer class and character encoding.

BinaryWriter binaryWriter = new BinaryWriter(outputStream, encoding);

Working of Binary Writer Works in C#:

  • In C#, Binary Writer is used to writing some binary data to a file or it is used to produce binary files. It helps us write primitive data types in double format to a stream. It also helps us write strings in a particular character encrypting.
  • When we are working with Binary Writer, it is important to include the System.IO namespace in the program. Now, we can easily create the object of the binary writer with the help of the ‘new’ operator and also pass a stream object to the constructor.
  • To produce an instance of Binary Writer, we usually provide a stream object to its constructor and at the same time, we can provide an optional parameter that states the encrypting to be used while writing the file. The encoding is not specified and remains UTF-8 by default.
  • Now, there is one more optional parameter that can be passed to the constructor while creating the object of Binary Writer. It is of type Boolean and it is used to identify whether the person wants the current stream to remain open or not.

Methods of Binary Writer:

Below are some methods of Binary Writer in C#:

Method Description
Write (Boolean)

This method is used to represent the one-byte Boolean value to the present stream. 

0 stands for false and 1 for true.

Write (Byte) This method is used to represent the unsigned byte to the present stream.
Write (Char)

This method is used to represent Unicode characters in the present stream.

And it also proceeds the current stream position based on character encrypting used.

Write (Decimal)

This method is used to represent a decimal value to the present stream.

It proceeds the position of the current stream by sixteen bytes.

Write (Double)

This method is used to represent an eight-byte floating value to the present stream.

It proceeds the position of the current stream by eight bytes.

Write (Int32)

This method is used to represent a four-byte signed integer to the present stream.

It proceeds the position of the current stream by four bytes.

Write (String)

This method is used to represent length prefixed string to present stream in the present encrypting of Binary Writer.

It also proceeds the current stream position based on character encrypting used.

Now, here is one method called write which basically writes a Boolean value to the stream as a one-byte value.

Example 1:

C#




using System;
using System.IO;
class binary
{
    const string fileName = "hello.dat";
    static void Main()
    {
       Write();
       Console.WriteLine("Binary Writer");
    }
    public static void Write()
    {
        using (BinaryWriter writer = new BinaryWriter(File.Open(fileName, 
                                                      FileMode.Create)))
        {
            writer.Write(helloworld);
            writer.Write(@"c:\Temp");
        }
    }
}


Output:

 

Code Explanation:

This C# program is used to illustrate binary writer. With the help of the binary writer class, the contents are written in the file. It provides a way that makes it easier to write primitive data types to a stream. The write() method writes a Boolean value to the stream as a one-byte value.

Example 2:

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:\New\First.txt", FileMode.Create)))
            {
                //writes the data to the stream
                bw.Write('Hello World');
                bw.Write('Welcome');
                bw.Write('c#');
                bw.Write("GeeksForGeeks");
                bw.Write(true);
                Console.WriteLine("Successfully Added");
                Console.ReadLine();
            }
        }
    }
}


Output:

Successfully Added


Previous Article
Next Article

Similar Reads

C# Program to Demonstrate the Use of GetCommandLineArgs() Method of Environment Class
Environment Class provides information about the current platform and manipulates, the current platform. It is useful for getting and setting various operating system-related information. We can use it in such a way that retrieves command-line arguments information, exit codes information, environment variable settings information, contents of the
3 min read
C# Program to Demonstrate the Use of FailFast() Method of Environment Class
Environment Class provides information about the current platform and manipulates, the current platform. It is useful for getting and setting various operating system-related information. We can use it in such a way that retrieves command-line arguments information, exit codes information, environment variable settings information, contents of the
3 min read
C# Program to Inherit an Abstract Class and Interface in the Same Class
Abstract Class is the way to achieve abstraction. It is a special class that never be instantiated directly. This class should contain at least one abstract method in it and mark by abstract keyword in the class definition. The main purpose of this class is to give a blueprint for derived classes and set some rules what the derived classes must imp
3 min read
C# Program to Demonstrate the Use of Exit() Method of Environment Classhttps://origin.geeksforgeeks.org/?p=705454
Environment Class provides information about the current platform and manipulates, the current platform. The Environment class is useful for getting and setting various operating system-related information. We can use it in such a way that retrieves command-line arguments information, exit codes information, environment variable settings informatio
3 min read
C# | How to use strings in switch statement
The switch statement is a multiway branch statement. It provides an easy way to forward execution to different parts of code based on the value of the expression. String is the only non-integer type which can be used in switch statement. Important points: Switching on strings can be more costly in term of execution than switching on primitive data
2 min read
C# | How to use multiple catch clause
The main purpose of the catch block is to handle the exception raised in the try block. This block is only going to execute when the exception raised in the program. In C#, You can use more than one catch block with the try block. Generally, multiple catch block is used to handle different types of exceptions means each catch block is used to handl
4 min read
C# | How to use Interface References
In C#, you are allowed to create a reference variable of an interface type or in other words, you are allowed to create an interface reference variable. Such kind of variable can refer to any object that implements its interface. An interface reference variable only knows that methods which are declared by its interface declaration. It does not all
5 min read
How to use Array.BinarySearch() Method in C# | Set -2
Array.BinarySearch() method is used to search a value in a sorted one dimensional array. The binary search algorithm is used by this method. This algorithm searches a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of
12 min read
How to use :: Namespace Alias Qualifier in C#
Namespace Alias Qualifier(::) makes the use of alias name in place of longer namespace and it provides a way to avoid ambiguous definitions of the classes. It is always positioned between two identifiers. The qualifier looks like two colons(::) with an alias name and the class name. It can be global. Thus it doesn't invoke a lookup in the aliased n
2 min read
How to use AcceptsReturn Property of TextBox in C#?
In TextBox, you are allowed to set a value which shows whether pressing the ENTER in a multiline TextBox control creates a new line of text in the TextBox control or activates the default button for the form by using AcceptsReturn property. If the value of this property is set to be true, then the ENTER key creates a new line of text in a multiline
3 min read
How to use AutoCheck property of CheckBox in C#?
The CheckBox control is the part of the windows form that is used to take input from the user. Or in other words, CheckBox control allows us to select single or multiple elements from the given list. You are allowed to set a value that determines the Checked or CheckedStates values and also the appearance of the CheckBox is set automatically when y
3 min read
Why to Use ASP.NET Server Controls in Place of HTML Controls?
Basically HTML controls are client side controls and ASP.NET controls are server side controls. We prefer ASP.NET controls as our web controls. As with the HTML controls we can't maintain the state ie the data is lost, we can say it as it does not provide state management. And while writing the code we can't access HTML controls from code behind th
4 min read
C# Program to Demonstrate the Use of the Method as a Condition in the LINQ
LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It gives the ability to .NET languages to generate queries to retrieve data from the data source. It removes the mismatch between programming languages and databases and the syntax used to create a query is the same no matter which type of data source is used. In this arti
2 min read
How to use HTML Agility Pack ?
Web scraping is a common task in programming, where developers need to extract data from websites for various purposes. Manually parsing HTML can be a tedious and error-prone process. The HTML Agility Pack provides a convenient solution for C# developers to parse and manipulate HTML documents easily. Table of Content HTML Agility PackSteps to insta
8 min read
C# | How to get TypeCode for the class String
GetTypeCode() method is used to get the TypeCode of the specified string. Here TypeCode enum represents a specific type of object. In TypeCode every data type is represented by a specific number like String is represented by 18, Int32 is represented by 9, etc. Syntax: public TypeCode GetTypeCode (); Return value: This method return an enumerated co
2 min read
C# | Class and Object
Class and Object are the basic concepts of Object-Oriented Programming which revolve around the real-life entities. A class is a user-defined blueprint or prototype from which objects are created. Basically, a class combines the fields and methods(member function which defines actions) into a single unit. In C#, classes support polymorphism, inheri
5 min read
C# | Sealed Class
Sealed classes are used to restrict the users from inheriting the class. A class can be sealed by using the sealed keyword. The keyword tells the compiler that the class is sealed, and therefore, cannot be extended. No class can be derived from a sealed class. The following is the syntax of a sealed class : sealed class class_name { // data members
4 min read
C# | Math Class Fields with Examples
In C#, the Math class provides the constants and the static methods for logarithmic, trigonometric, and other mathematical functions. Math class has two fields as follows: Math.E FieldMath.PI FieldMath.E Field This field represents the natural logarithmic base, specified by the constant, e. Syntax: public const double E Program 1: To illustrate the
3 min read
C# | Math Class
In C#, Math class comes under the System namespace. It is used to provide static methods and constants for logarithmic, trigonometric, and other useful mathematical functions. It is a static class and inherits the object class. public static class Math Fields A field is a variable that is declared in a class or struct. These are considered as the m
4 min read
C# | ListDictionary Class
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } ListDictiona
5 min read
C# | HybridDictionary Class
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } HybridDictio
5 min read
C# | ArrayList Class
.arraylist-table { border-collapse: collapse; width: 100%; } .arraylist-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .arraylist-table th { border: 1px solid #5fb962; padding: 8px; } .arraylist-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .arraylist-table tr:nth-child(odd) { background-color
7 min read
C# | BitArray Class
.bitarray-table { border-collapse: collapse; width: 100%; } .bitarray-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .bitarray-table th { border: 1px solid #5fb962; padding: 8px; } .bitarray-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .bitarray-table tr:nth-child(odd) { background-color: #ff
6 min read
C# | StringDictionary Class
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } StringDictio
5 min read
C# | OrderedDictionary Class
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } OrderedDicti
5 min read
C# | String class
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } In C#, a str
9 min read
C# | SortedSet Class
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } SortedSet cl
6 min read
C# | StringCollection Class
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } StringCollec
5 min read
C# | Creating an empty case-sensitive HybridDictionary Class
HybridDictionary() creates an empty case-sensitive HybridDictionary. Syntax: public HybridDictionary (); Below given are some examples to understand the implementation in a better way: Example 1: C/C++ Code // C# code to create an empty // case-sensitive HybridDictionary. using System; using System.Collections; using System.Collections.Specialized;
2 min read
C# | LinkedList Class
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } LinkedList
5 min read
Article Tags :
three90RightbarBannerImg