How to do basic file I/O in Visual Basic 2005 or in Visual Basic .NET

Article translations Article translations
Article ID: 304427 - View products that this article applies to.
This article was previously published under Q304427
For a Microsoft Visual C# .NET version of this article, see 304430.
For a Microsoft Visual C++ .NET version of this article, see 307398.
Expand all | Collapse all

On This Page

Summary

This step-by-step article shows you how to do six basic file input/output (I/O) operations in Microsoft Visual Basic 2005 or in Microsoft Visual Basic .NET. If you are new to .NET, you will find that the object model for file operations in .NET is similar to the FileSystemObject (FSO) that is popular with many Visual Studio 6.0 developers. To make the transition easier, the functionality that is demonstrated in this article is based on the following Microsoft Knowledge Base article:
186118 How to use FileSystemObject with Visual Basic
You can still use the FileSystemObject in .NET. Because the FileSystemObject is a Component Object Model (COM) component, .NET requires that access to the object be through the Interop layer. .NET generates a wrapper for the component for you if you want to use it. However, the File, FileInfo, Directory, DirectoryInfo classes, and other related classes in the .NET Framework, offer functionality that is not available with the FSO, without the overhead of the Interop layer.

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
  • Microsoft Windows Server 2003, Microsoft Windows 2000 Professional, Windows 2000 Server, Windows 2000 Advanced Server, or Microsoft Windows NT 4.0 Server
  • Microsoft Visual Studio 2005 or Microsoft Visual Studio .NET
  • Microsoft Visual Studio 2005 Software Development Kit (SDK) Quickstarts or Microsoft Visual Studio .NET SDK Quickstarts

Demonstrated file I/O operations

The examples in this article describe basic file I/O operations. The "Step-by-step example" section describes how to create a sample program that demonstrates the following file I/O operations:
  • Read a text file
  • Write a text file
  • View file information
  • List disk drives
  • List subfolders
  • List files

Read a text file

The following sample code uses a StreamReader class to read the System.ini file. The contents of the file are added to a ListBox control. The try...catch block is used to alert the program if the file is empty. There are many ways to determine when the end of the file is reached; this sample uses the Peek method to examine the next line before reading it.
    Dim reader As StreamReader = _
    New StreamReader(winDir & "\system.ini")
    Try
        Me.ListBox1.Items.Clear()
        Do 
            Me.ListBox1.Items.Add(reader.ReadLine)
        Loop Until reader.Peek = -1

    Catch
        Me.ListBox1.Items.Add("File is empty")

    Finally
        reader.Close()
    End Try
				

Write a text file

This sample code uses a StreamWriter class to create and write to a file. If you have an existing file, you can open it in the same way.
    Dim writer As StreamWriter = _
    New StreamWriter("c:\KBTest.txt")
    writer.WriteLine("File created using StreamWriter class.")
    writer.Close()
				

View file information

This sample code uses a FileInfo object to access a file's properties. Notepad.exe is used in this example. The properties appear in a ListBox control.
    Dim FileProps As FileInfo = New FileInfo(winDir & "\notepad.exe")
    With Me.ListBox1.Items
        .Clear()
        .Add("File Name = " & FileProps.FullName)
        .Add("Creation Time = " & FileProps.CreationTime)
        .Add("Last Access Time = " & FileProps.LastAccessTime)
        .Add("Last Write Time = " & FileProps.LastWriteTime)
        .Add("Size = " & FileProps.Length)
    End With
    FileProps = Nothing
				

List disk drives

This sample code uses the Directory and Drive classes to list the logical drives on a system. For this sample, the results appear in a ListBox control.
    Dim dirInfo As Directory
    Dim drive As String
    Me.ListBox1.Items.Clear()
    Dim drives() As String = dirInfo.GetLogicalDrives()
    For Each drive In drives
        Me.ListBox1.Items.Add(drive)
    Next
				

List subfolders

This sample code uses the GetDirectories method of the Directory class to get a list of folders.
    Dim dir As String
    Me.ListBox1.Items.Clear()
    Dim dirs() As String = Directory.GetDirectories(winDir)
    For Each dir In dirs
        Me.ListBox1.Items.Add(dir)
    Next
				

List files

This sample code uses the GetFiles method of the Directory class to get a list of files.
    Dim file As String
    Me.ListBox1.Items.Clear()
    Dim files() As String = Directory.GetFiles(winDir)
    For Each file In files
        Me.ListBox1.Items.Add(file)
    Next
				
Many things can go wrong when a user gains access to files. The files may not exist, the files may be in use, or users may not have rights on the files of folders that they are trying to access. It is important to consider these possibilities when you write code and to handle the exceptions that may be generated.

Step-by-step example

  1. In Visual Basic 2005 or in Visual Basic .NET, create a new Windows Application. By default, Form1 is created.
  2. Open the code window for Form1.
  3. Delete all of the code in the Code-Behind Editor.
  4. Paste the following sample code into the Code-Behind Editor window.
    Option Strict On
    Imports System.IO
    
    Public Class Form1
        Inherits System.Windows.Forms.Form
        Private winDir As String
    #Region " Windows Form Designer generated code "
    
        Public Sub New()
            MyBase.New()
    
            'Windows Form Designer requires this call.
            InitializeComponent()
    
            'Add any initialization after the InitializeComponent() call.
    
        End Sub
    
        'Form overrides dispose to clean up the component list.
    
        Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
            If disposing Then
                If Not (components Is Nothing) Then
                    components.Dispose()
                End If
            End If
            MyBase.Dispose(disposing)
        End Sub
                            Friend WithEvents ListBox1 As System.Windows.Forms.ListBox
        Friend WithEvents Button3 As System.Windows.Forms.Button
        Friend WithEvents Button5 As System.Windows.Forms.Button
        Friend WithEvents Button4 As System.Windows.Forms.Button
        Friend WithEvents Button2 As System.Windows.Forms.Button
        Friend WithEvents Button1 As System.Windows.Forms.Button
        Friend WithEvents Button6 As System.Windows.Forms.Button
        
        'Windows Form Designer requires this call.
        Private components As System.ComponentModel.Container
    
        'NOTE: Windows Form Designer requires the following procedure.
        'You can use the Windows Form Designer to modify it; however, do not
        'use the Code Editor to modify it.
        <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
            Me.Button2 = New System.Windows.Forms.Button()
            Me.Button3 = New System.Windows.Forms.Button()
            Me.ListBox1 = New System.Windows.Forms.ListBox()
            Me.Button4 = New System.Windows.Forms.Button()
            Me.Button5 = New System.Windows.Forms.Button()
            Me.Button1 = New System.Windows.Forms.Button()
            Me.Button6 = New System.Windows.Forms.Button()
            Me.SuspendLayout()
            '
            'Button2
            '
            Me.Button2.Location = New System.Drawing.Point(272, 64)
            Me.Button2.Name = "Button2"
            Me.Button2.Size = New System.Drawing.Size(136, 23)
            Me.Button2.TabIndex = 1
            Me.Button2.Text = "Button2"
            '
            'Button3
            '
            Me.Button3.Location = New System.Drawing.Point(272, 96)
            Me.Button3.Name = "Button3"
            Me.Button3.Size = New System.Drawing.Size(136, 23)
            Me.Button3.TabIndex = 2
            Me.Button3.Text = "Button3"
            '
            'ListBox1
            '
            Me.ListBox1.Location = New System.Drawing.Point(16, 16)
            Me.ListBox1.Name = "ListBox1"
            Me.ListBox1.Size = New System.Drawing.Size(240, 238)
            Me.ListBox1.TabIndex = 5
            '
            'Button4
            '
            Me.Button4.Location = New System.Drawing.Point(272, 128)
            Me.Button4.Name = "Button4"
            Me.Button4.Size = New System.Drawing.Size(136, 23)
            Me.Button4.TabIndex = 3
            Me.Button4.Text = "Button4"
            '
            'Button5
            '
            Me.Button5.Location = New System.Drawing.Point(272, 160)
            Me.Button5.Name = "Button5"
            Me.Button5.Size = New System.Drawing.Size(136, 23)
            Me.Button5.TabIndex = 4
            Me.Button5.Text = "Button5"
            '
            'Button1
            '
            Me.Button1.Location = New System.Drawing.Point(272, 32)
            Me.Button1.Name = "Button1"
            Me.Button1.Size = New System.Drawing.Size(136, 23)
            Me.Button1.TabIndex = 0
            Me.Button1.Text = "Button1"
            '
            'Button6
            '
            Me.Button6.Location = New System.Drawing.Point(272, 192)
            Me.Button6.Name = "Button6"
            Me.Button6.Size = New System.Drawing.Size(136, 23)
            Me.Button6.TabIndex = 6
            Me.Button6.Text = "Button6"
            '
            'Form1
            '
            Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
            Me.ClientSize = New System.Drawing.Size(416, 341)
            Me.Controls.AddRange(New System.Windows.Forms.Control() _
               {Me.Button6, Me.ListBox1, Me.Button5, Me.Button4, _
               Me.Button3, Me.Button2, Me.Button1})
            Me.Name = "Form1"
            Me.Text = "Form1"
            Me.ResumeLayout(False)
    
        End Sub
    
    #End Region
    
        Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
          Handles MyBase.Load
            Me.Button1.Text = "Read Text File"
            Me.Button2.Text = "Write Text File"
            Me.Button3.Text = "View File Information"
            Me.Button4.Text = "List Drives"
            Me.Button5.Text = "List Subfolders"
            Me.Button6.Text = "List Files"
            winDir = System.Environment.GetEnvironmentVariable("windir")
        End Sub
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
          Handles Button1.Click
            'Demonstrates how to read a file by using StreamReader 
            'Uses System.ini as an example
            'try...catch is used to detect a 0 byte file.
            Dim reader As StreamReader = _
                New StreamReader(winDir & "\system.ini")
            Try
                Me.ListBox1.Items.Clear()
                Do 'Until reader.Peek = -1
                    Me.ListBox1.Items.Add(reader.ReadLine)
                Loop Until reader.Peek = -1
    
            Catch
                Me.ListBox1.Items.Add("File is empty")
    
            Finally
                reader.Close()
            End Try
        End Sub
    
        Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
          Handles Button4.Click
            'Demonstrates how to obtain a list of disk drives
            Dim dirInfo As Directory
            Dim drive As String
            Me.ListBox1.Items.Clear()
            Dim drives() As String = dirInfo.GetLogicalDrives()
            For Each drive In drives
                Me.ListBox1.Items.Add(drive)
            Next
        End Sub
    
        Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
          Handles Button3.Click
            'Demonstrates how to access file properties. You can access folder properties
            'in the same way. More properties are available through the FileInfo class
            'than are demonstrated here. 
            'You can also use the Directory class to obtain this information. 
            Dim FileProps As FileInfo = New FileInfo(winDir & "\notepad.exe")
            With Me.ListBox1.Items
                .Clear()
                .Add("File Name = " & FileProps.FullName)
                .Add("Creation Time = " & FileProps.CreationTime)
                .Add("Last Access Time = " & FileProps.LastAccessTime)
                .Add("Last Write TIme = " & FileProps.LastWriteTime)
                .Add("Size = " & FileProps.Length)
            End With
            FileProps = Nothing
        End Sub
    
        Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
          Handles Button2.Click
            'Demonstrates how to create and write to a text file
            Dim writer As StreamWriter = _
                New StreamWriter("c:\KBTest.txt")
            writer.WriteLine("File created using StreamWriter class.")
            writer.Close()
            Me.ListBox1.Items.Clear()
            Me.ListBox1.Items.Add("File Written to C:\KBTest.txt")
        End Sub
    
        Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
          Handles Button5.Click
            'Demonstrates how to get a list of folders (example uses Windows folder)
            Dim dir As String
            Me.ListBox1.Items.Clear()
            Dim dirs() As String = Directory.GetDirectories(winDir)
            For Each dir In dirs
                Me.ListBox1.Items.Add(dir)
            Next
        End Sub
    
        Private Sub Button6_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
          Handles Button6.Click
            'Demonstrates how to get a list of files (example uses Windows folder)
            Dim file As String
            Me.ListBox1.Items.Clear()
            Dim files() As String = Directory.GetFiles(winDir)
            For Each file In files
                Me.ListBox1.Items.Add(file)
            Next
        End Sub
    End Class
    					
    Note You must change the code in Visual Basic 2005. By default, Visual Basic creates two files for the project when you create a Windows Forms project. If the form is named Form1, the two files that represent the form are named Form1.vb and Form1.Designer.vb. You write the code in the Form1.vb file. The Windows Forms Designer writes the code in the Form1.Designer.vb file. The Windows Forms Designer uses the partial keyword to divide the implementation of Form1 into two separate files. This behavior prevents the designer-generated code from being interspersed with your code.

    For more information about the new Visual Basic 2005 language enhancements, visit the following Microsoft Developer Network (MSDN) Web site:
    http://msdn2.microsoft.com/en-us/library/ms379584(vs.80).aspx
    For more information about partial classes and the Windows Forms Designer, visit the following MSDN Web site:
    http://msdn2.microsoft.com/en-us/library/ms171843.aspx
  5. Press F5 to build and then run the program. Click the buttons to view the different actions. When you view the sample code, you may want to collapse the area named Windows Form Designer Generated Code to hide this code.

Properties

Article ID: 304427 - Last Review: October 15, 2012 - Revision: 4.0
Applies to
  • Microsoft Visual Basic 2005
  • Microsoft Visual Basic .NET 2003 Standard Edition
  • Microsoft Visual Basic .NET 2002 Standard Edition
Keywords: 
kbvs2005swept kbvs2005applies kbhowtomaster kbnokeyword kbprod2web KB304427

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com