Windows apps
Collapse the table of content
Expand the table of content
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

How to: Read and Write to a Newly Created Data File 

The BinaryWriter and BinaryReader classes are used for writing and reading data, rather than character strings. The following code example demonstrates writing data to and reading data from a new, empty file stream ( After creating the data file in the current directory, the associated BinaryWriter and BinaryReader are created, and the BinaryWriter is used to write the integers 0 through 10 to, which leaves the file pointer at the end of the file. After setting the file pointer back to the origin, the BinaryReader reads out the specified content.


Option Explicit On 
Option Strict On
Imports System
Imports System.IO
Class MyStream
    Private Const FILE_NAME As String = ""
    Public Shared Sub Main()
        ' Create the new, empty data file.
        If File.Exists(FILE_NAME) Then
            Console.WriteLine("{0} already exists!", FILE_NAME)
        End If
        Dim fs As New FileStream(FILE_NAME, FileMode.CreateNew)
        ' Create the writer for data.
        Dim w As New BinaryWriter(fs)
        ' Write data to
        Dim i As Integer
        For i = 0 To 10
        Next i
        ' Create the reader for data.
        fs = New FileStream(FILE_NAME, FileMode.Open, FileAccess.Read)
        Dim r As New BinaryReader(fs)
        ' Read data from
        For i = 0 To 10
        Next i
    End Sub
End Class

Robust Programming

If already exists in the current directory, an IOException is thrown. Use FileMode.Create to always create a new file without throwing an IOException.

See Also

© 2018 Microsoft