Skip to content
Permalink
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 ms.date ms.technology dev_langs helpviewer_keywords ms.assetid
How to: Read and write to a newly created data file
01/21/2019
dotnet-standard
csharp
vb
cpp
streams, reading and writing data
BinaryReader class, examples
I/O [.NET Framework], reading data
I/O [.NET Framework], writing data
BinaryWriter class, examples
e209d949-31e8-44ea-8e38-87f9093f3093

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 Test.data 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 Test.data, 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 Test.data 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.

Example

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

See also

You can’t perform that action at this time.