C# BinaryWriter

In c#, BinaryWriter is a class of System.IO namespace and it is useful to write binary information to the stream with a particular encoding. By default, the BinaryWriter will use UTF-8 Encoding unless we specify other encodings.

 

Now, we will see how to use BinaryWriter class in c# to write binary information to the file with examples.

C# BinaryWriter Example

Following is the example of writing a text to the file in binary form using BinaryWriter object in c#.

 

using System.IO;

 

namespace TutlaneExamples

{

    class Program

    {

        static void Main(string[] args)

        {

            string fpath = @"D:\Test.txt";

            // Check file if exists

            if (File.Exists(fpath))

            {

                File.Delete(fpath);

            }

            using (BinaryWriter bw = new BinaryWriter(File.Open(fpath,FileMode.Create)))

            {

                bw.Write(1.25);

                bw.Write("Welcome to Tutlane");

                bw.Write(10);

                bw.Write(true);

                bw.Write("test");

            }

        }

    }

}

If you observe the above example, we imported a System.IO namespace in our example to access File, FileStream & BinaryWriter objects to delete, create and write a text to file.

 

When we execute the above example, it will create a new “Test.txt” file in D drive with required text like as shown below.

 

C# BinaryWriter Example Result

 

This is how we can create, delete and add text to files using File, FileStream & BinaryWriter objects in c#.

 

PREVIOUS

C# StreamReader
 

NEXT

C# BinaryReader  
 

Topics Covered