Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

BinaryWriter.Write Method (Byte[], Int32, Int32)

Writes a region of a byte array to the current stream.

Namespace:  System.IO
Assemblies:   System.IO (in System.IO.dll)
  mscorlib (in mscorlib.dll)

public virtual void Write(
	byte[] buffer,
	int index,
	int count


Type: System.Byte[]

A byte array containing the data to write.

Type: System.Int32

The starting point in buffer at which to begin writing.

Type: System.Int32

The number of bytes to write.


The buffer length minus index is less than count.


buffer is null.


index or count is negative.


An I/O error occurs.


The stream is closed.

For a list of common I/O tasks, see Common I/O Tasks.

The following code example shows how to write binary data using memory as a backing store, and then verify that the data was written correctly.

using System;
using System.IO;

namespace BinaryRW
    class Program
        static void Main(string[] args)
            const int arrayLength = 1000;
            byte[] dataArray = new byte[arrayLength];
            byte[] verifyArray = new byte[arrayLength];

            new Random().NextBytes(dataArray);

            using (BinaryWriter binWriter = new BinaryWriter(new MemoryStream()))
                Console.WriteLine("Writing the data.");
                binWriter.Write(dataArray, 0, arrayLength);

                using (BinaryReader binReader = new BinaryReader(binWriter.BaseStream))
                    binReader.BaseStream.Position = 0;

                    if (binReader.Read(verifyArray, 0, arrayLength) != arrayLength)
                        Console.WriteLine("Error writing the data.");

            for (int i = 0; i < arrayLength; i++)
                if (verifyArray[i] != dataArray[i])
                    Console.WriteLine("Error writing the data.");

            Console.WriteLine("The data was written and verified.");

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

XNA Framework

Supported in: 3.0, 2.0, 1.0

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8

Portable Class Library

Supported in: Portable Class Library
© 2015 Microsoft