This documentation is archived and is not being maintained.

File Access Through BinaryReader and BinaryWriter Classes

Visual Studio .NET 2003

The BinaryReader and BinaryWriter classes may be more familiar to Visual Basic users as DataReader and DataWriter. Although the names have been changed for the System.IO Namespace model, the underlying functionality remains the same. The BinaryReader class is used for reading strings and elementary data types, whereas the BinaryWriter class writes elementary types in binary data from a sequential text file (sometimes referred to as a text stream).

Security Note   When writing to files, an application may need to create a file if the file to which it is trying to write does not exist. To do so, it needs permission for the directory in which the file is to be created. However, if the file already exists, the application only needs Write permission to the file itself. Wherever possible, it is more secure to create the file during deployment and only grant Write permission to that file, rather than to the entire directory. It is also more secure to write data to user directories than to the root directory or the Program Files directory.

The following example demonstrates how to read and write to a newly created file:

Imports System.IO
Private Sub MyButton_Click (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyButton.Click)
' Code throws an exception if the file already exists.
   Dim fs As FileStream = New FileStream("c:\data.txt", _
   Dim w As BinaryWriter = New BinaryWriter(fs)
   Dim r As BinaryReader = New BinaryReader(fs)
   Dim i As Integer

   ' Takes the series of integers and stores them in a buffer.
   For i = 0 To 11

   ' Sets the pointer to the beginning of the file.
   w.Seek(0, SeekOrigin.Begin)

   ' Writes the contents of the buffer to the console.
   For i = 0 To 11

   ' Reads from file and writes it one character at a time.
   For i = 0 To 11
      Dim NewString As String
      NewString =
End Sub
Note   Both BinaryReader and BinaryWriter read and write information as binary rather than text. To process text information, see File Access Through StreamReader and StreamWriter Classes.

See Also

File Access with Visual Basic .NET | File Access Through the FileStream Class | File Access Through StreamReader and StreamWriter Classes | Drive and Folder Access | Serialization | System.IO Namespace | Code: Reading from a Text File (Visual Basic) | Code: Writing Text to a File (Visual Basic)