Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

Choosing Among File I/O Options in Visual Basic .NET

Visual Studio .NET 2003

Visual Basic .NET presents three possible approaches to file I/O for the programmer: runtime methods contained in Visual Basic .NET; FileSystemObject; and the Common Language Runtime File methods.

File Methods in Visual Basic .NET

The Microsoft.VisualBasic namespace is populated by a host of functions and methods familiar to users of earlier versions of Visual Basic. While some names have shifted slightly, the vast majority are the same: Dir, Input, Print, Seek, Write, and so forth.

A few changes have occurred in the functions used in these different types of file access. The most noticeable change is the substitution of the FilePut/FilePutObject and FileGet/FileGetObject functions for Put and Get. In Visual Basic .NET, FilePut and FileGet map to the Put and Get functions; FilePutObject and FileGetObject are used to write an object of type Object (the equivalent of Variant type in earlier versions of Visual Basic) to the file. For more information, see Variant Type Constant Changes in Visual Basic .NET.

Advantages and Disadvantages

Two principal advantages of the functions provided by the Visual Basic .NET runtime are familiarity and ease of use. The core functionality of Visual Basic .NET, which remains familiar, intuitive, and flexible, provides a comfortable launching place for exploration of .NET.

Similarly, upgrading a program written in an earlier version of Visual Basic to its .NET counterpart or creating an application that interacts well with applications written in earlier versions should prove relatively simple. For more information on upgrading previous versions of code, see Preparing a Visual Basic 6.0 Application for Upgrading.

The Visual Basic .NET functions also provide binary file access, which the FileSystemObject object (described in the next section) does not, making it a better choice when working with variable length fields.

Finally, there are no special considerations, such as the need to import namespaces, when using the Visual Basic .NET built-in file I/O functions from within Visual Basic .NET.

The fact that Visual Basic .NET file I/O functions do not support writing types other than String, Date, Integer, Long, Single, Double, Decimal, and structures and arrays of those types poses a disadvantage when using these functions. Beyond this, classes cannot be serialized and performance in such cases may not be as optimal as using the System.IO classes directly.

Code Examples

The following example checks to see if a file exists and if so, uses the FileCopy function to copy it to a new file.

Private Sub CopyFiles()
   Dim checkFile As String
   checkFile = Dir$("c:\test.txt")
   If checkFile = "test.txt"
      FileCopy "c:\test.txt", "c:\new.txt"
   End If
End Sub

The following example uses the FilePut function, which corresponds to the Put function in previous versions of Visual Basic, to write data to a file. Three records of the structure CustomerRecord are written to the file.

Structure CustomerRecord 
   Public OrderNumber As Integer
   Public Name As String
   Public OrderDate As Date
End Structure

Sub WriteData()
   Dim MyRecord As CustomerRecord
   Dim RecordNumber As Integer
   Dim RecordDate As Date
   ' Open file for random access.
   FileOpen(1, "C:\TESTFILE.txt", OpenMode.Binary)
   For RecordNumber = 1 To 3   ' Loop 3 times.
      MyRecord.OrderNumber = RecordNumber    ' Define OrderNumber.
      MyRecord.OrderDate = RecordDate          ' Define OrderDate.
      MyRecord.Name = "My Name" & RecordNumber ' Create a string.
      FilePut(1, MyRecord)                 ' Write record to file.
   Next RecordNumber
End Sub

.NET Framework Classes

The System.IO namespace contains File and Directory classes, which provide the basic functionality that manipulates files and directories. Because all the methods are static or shared members of these objects, you can use them directly without creating an instance of the class first.

Advantages and Disadvantages

Venturing into the common language runtime yields a rich class library. For example, the System.IO namespace provides services beyond basic file I/O, such as the FileSystemWatcher class, which allows you to monitor changes to files, and the FileInfo and DirectoryInfo classes, which allow you to gather information about a specified file or directory. For more information, see FileSystemWatcher Class, FileInfo Class, and DirectoryInfo Class.

Similarly, the common language runtime offers the FileIOPermission class, which allows you to control access to files and directories. This may be particularly important for developers working with Web Forms, which by default run within the context of a special local user named ASPNET, which is created as part of the ASP.NET and .NET Framework installations. When such an application requests access to a resource, that request is made within the context of that user. However, by default, the ASPNET user has limited permissions, which may prevent them from performing actions such as writing to a file from a Web application. For more information, see FileIOPermission Class.

The common language runtime is also compatible with other .NET languages, such as Visual C#™, and may aid in achieving consistency across applications, which may be particularly important at the enterprise level.

Lack of familiarity with the common language runtime may create difficulties for a Visual Basic programmer who is still becoming familiar with these new approaches. If you are in that category, you may prefer to rely on the methods you know well.

Code Examples

The following example uses the StreamReader class to read the contents of a text file.

Imports System
Imports System.IO
Function ReadTextFile(ByVal path As String) As String
   Dim sr As System.IO.StreamReader
   Dim Contents As String
   sr = New StreamReader(path)
   Contents = sr.ReadToEnd()
   Return Contents
End Function

The following code reverses the previous example, using the same approach with the StreamWriter class to write to a text file.

Imports System
Imports System.IO
Sub WriteTextFile(ByVal path As String, ByVal value As String)
Dim sr As StreamWriter
Dim Contents As String
   sr = New StreamWriter(path)
End Sub


Like the functions and methods provided by the Microsoft.VisualBasic namespace, the FileSystemObject object will be familiar to users of previous versions of Visual Basic.

The FileSystemObject (FSO) model presents files, directories, and drives as COM objects, each with their own properties and methods. You can create and manipulate these objects and use their properties to discover information such as a directory's contents, a file's size, the time an object was created, and so on. You access the objects representing the system's files, directories, and drives by creating and accessing an instance of the FileSystemObject object.

The FSO object model, which is in the Microsoft Scripting Runtime type library (Scrrun.dll), supports the creation and manipulation of text files through the TextStream object. For more information, see TextStream Object. The FileStream class exposes a stream around a file, allowing both synchronous and asynchronous read and write operations on a file system as well as buffering input and output for better performance. Information is written to the buffer and the contents of the buffer are written to the file only when the buffer is full or a Close method is called. For more information, see FileStream Class.

Advantages and Disadvantages

The primary advantage of the FSO is that it gathers a number of file I/O functions into a single object. By creating an instance of the object, you can access its methods and properties.

The FSO object model is also well suited to threading. It provides a constructor for asynchronous I/O, such as when using the BeginRead and BeginWrite methods, which enables the main thread to continue, allowing the user to process the data later. Multiple I/O requests can be pending at the same time.

However, there are several disadvantages to the FSO. As noted earlier, it works only with text files. To manipulate binary files, you must use pointers to an address in memory, or byte arrays, which are not supported by the object.

Moreover, when you read or write a large amount of content, the information stored in the buffer may create a big memory hit. Finally, you cannot manage permissions or file and folder attributes.

Code Example

The following example uses an instance of the FileSystemObject object to read a file and write its contents.

Public Class UsesScripting
   Public Shared Sub Main()
      Dim fileSystem As New Scripting.FileSystemObject()
      Dim file As Scripting.TextStream
      file = fileSystem.OpenTextFile("c:\test.txt", _
      Scripting.IOMode.ForReading, False, _
      Dim contents As String = file.ReadAll()
   End Sub
End Class

See Also

File Access with Visual Basic .NET | File Access with Visual Basic Run-Time Functions | Accessing Files with FileSystemObject

© 2015 Microsoft