| title | ms.custom | ms.date | ms.prod | ms.reviewer | ms.suite | ms.technology | ms.tgt_pltfrm | ms.topic | helpviewer_keywords | ms.assetid | caps.latest.revision | author | ms.author | manager | |||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
How to: Read and Write to a Newly Created Data File |
03/30/2017 |
.net |
dotnet-standard |
article |
|
e209d949-31e8-44ea-8e38-87f9093f3093 |
16 |
mairaw |
mairaw |
wpickett |
How to: Read and Write to a Newly Created Data File
The xref:System.IO.BinaryWriter and xref:System.IO.BinaryReader?displayProperty=nameWithType classes are used for writing and reading data rather than character strings. The following example demonstrates how to write data to, and read data from, a new, empty file stream called Test.data. After creating the data file in the current directory, the associated xref:System.IO.BinaryWriter and xref:System.IO.BinaryReader objects are created, and the xref:System.IO.BinaryWriter object is used to write the integers 0 through 10 to Test.data, which leaves the file pointer at the end of the file. After setting the file pointer back to the origin, the xref:System.IO.BinaryReader object reads out the specified content.
Example
[!code-cppSystem.IO.BinaryReaderWriter#7] [!code-csharpSystem.IO.BinaryReaderWriter#7] [!code-vbSystem.IO.BinaryReaderWriter#7]
Robust Programming
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 when you initialize the file stream to always create a new file without throwing an exception.
See Also
xref:System.IO.BinaryReader
xref:System.IO.BinaryWriter
xref:System.IO.FileStream
xref:System.IO.FileStream.Seek%2A?displayProperty=nameWithType
xref:System.IO.SeekOrigin
How to: Enumerate Directories and Files
How to: Open and Append to a Log File
How to: Read Text from a File
How to: Write Text to a File
How to: Read Characters from a String
How to: Write Characters to a String
File and Stream I-O