Skip to content
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
42 lines (37 sloc) 2.76 KB
title dev_langs helpviewer_keywords ms.assetid
How to: Read and write to a newly created data file
streams, reading and writing data
BinaryReader class, examples
I/O [.NET Framework], reading data
I/O [.NET Framework], writing data
BinaryWriter class, examples

How to: Read and write to a newly created data file

The xref:System.IO.BinaryWriter?displayProperty=nameWithType and xref:System.IO.BinaryReader?displayProperty=nameWithType classes are used for writing and reading data other than character strings. The following example shows how to create an empty file stream, write data to it, and read data from it.

The example creates a data file called in the current directory, creates the associated xref:System.IO.BinaryWriter and xref:System.IO.BinaryReader objects, and uses the xref:System.IO.BinaryWriter object to write the integers 0 through 10 to, which leaves the file pointer at the end of the file. The xref:System.IO.BinaryReader object then sets the file pointer back to the origin and reads out the specified content.

[!NOTE] If already exists in the current directory, an xref:System.IO.IOException exception is thrown. Use the file mode option xref:System.IO.FileMode.Create?displayProperty=nameWithType rather than xref:System.IO.FileMode.CreateNew?displayProperty=nameWithType to always create a new file without throwing an exception.


[!code-csharpSystem.IO.BinaryReaderWriter#7] [!code-vbSystem.IO.BinaryReaderWriter#7]

See also

You can’t perform that action at this time.