Windows Dev Center

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 System.IO.BinaryReader 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 After creating the data file in the current directory, the associated BinaryWriter and BinaryReader objects are created, and the BinaryWriter object 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 object reads out the specified content.

Imports System
Imports System.IO

Class MyStream
    Private Const FILE_NAME As String = "" 

    Public Shared Sub Main()
        If File.Exists(FILE_NAME) Then
            Console.WriteLine("{0} already exists!", FILE_NAME)
        End If 

        Using fs As New FileStream(FILE_NAME, FileMode.CreateNew)
            Using w As New BinaryWriter(fs)
                For i As Integer = 0 To 10
            End Using 
        End Using 

        Using fs As New FileStream(FILE_NAME, FileMode.Open, FileAccess.Read)
            Using r As New BinaryReader(fs)
                For i As Integer = 0 To 10
            End Using 
        End Using 
    End Sub 
End Class

If already exists in the current directory, an IOException exception is thrown. Use the file mode option FileMode.Create when you initialize the file stream to always create a new file without throwing an exception.

© 2015 Microsoft