Microsoft KB Archive/304427

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

Article ID: 304427

Article Last Modified on 5/11/2007

-

APPLIES TO


 * Microsoft Visual Basic 2005
 * Microsoft Visual Basic .NET 2003 Standard Edition
 * Microsoft Visual Basic .NET 2002 Standard Edition

-



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.



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 &quot;Step-by-step example&quot; 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 & &quot;\system.ini&quot;) Try Me.ListBox1.Items.Clear Do            Me.ListBox1.Items.Add(reader.ReadLine) Loop Until reader.Peek = -1

Catch Me.ListBox1.Items.Add(&quot;File is empty&quot;)

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(&quot;c:\KBTest.txt&quot;) writer.WriteLine(&quot;File created using StreamWriter class.&quot;) 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 & &quot;\notepad.exe&quot;) With Me.ListBox1.Items .Clear .Add(&quot;File Name = &quot; & FileProps.FullName) .Add(&quot;Creation Time = &quot; & FileProps.CreationTime) .Add(&quot;Last Access Time = &quot; & FileProps.LastAccessTime) .Add(&quot;Last Write Time = &quot; & FileProps.LastWriteTime) .Add(&quot;Size = &quot; & 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
 In Visual Basic 2005 or in Visual Basic .NET, create a new Windows Application. By default, Form1 is created. Open the code window for Form1. Delete all of the code in the Code-Behind Editor.  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
 * 1) Region &quot; Windows Form Designer generated code &quot;

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.  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 = &quot;Button2&quot; Me.Button2.Size = New System.Drawing.Size(136, 23) Me.Button2.TabIndex = 1 Me.Button2.Text = &quot;Button2&quot; '       'Button3 '       Me.Button3.Location = New System.Drawing.Point(272, 96) Me.Button3.Name = &quot;Button3&quot; Me.Button3.Size = New System.Drawing.Size(136, 23) Me.Button3.TabIndex = 2 Me.Button3.Text = &quot;Button3&quot; '       'ListBox1 '       Me.ListBox1.Location = New System.Drawing.Point(16, 16) Me.ListBox1.Name = &quot;ListBox1&quot; 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 = &quot;Button4&quot; Me.Button4.Size = New System.Drawing.Size(136, 23) Me.Button4.TabIndex = 3 Me.Button4.Text = &quot;Button4&quot; '       'Button5 '       Me.Button5.Location = New System.Drawing.Point(272, 160) Me.Button5.Name = &quot;Button5&quot; Me.Button5.Size = New System.Drawing.Size(136, 23) Me.Button5.TabIndex = 4 Me.Button5.Text = &quot;Button5&quot; '       'Button1 '       Me.Button1.Location = New System.Drawing.Point(272, 32) Me.Button1.Name = &quot;Button1&quot; Me.Button1.Size = New System.Drawing.Size(136, 23) Me.Button1.TabIndex = 0 Me.Button1.Text = &quot;Button1&quot; '       'Button6 '       Me.Button6.Location = New System.Drawing.Point(272, 192) Me.Button6.Name = &quot;Button6&quot; Me.Button6.Size = New System.Drawing.Size(136, 23) Me.Button6.TabIndex = 6 Me.Button6.Text = &quot;Button6&quot; '       '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 = &quot;Form1&quot; Me.Text = &quot;Form1&quot; Me.ResumeLayout(False)

End Sub


 * 1) End Region

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles MyBase.Load Me.Button1.Text = &quot;Read Text File&quot; Me.Button2.Text = &quot;Write Text File&quot; Me.Button3.Text = &quot;View File Information&quot; Me.Button4.Text = &quot;List Drives&quot; Me.Button5.Text = &quot;List Subfolders&quot; Me.Button6.Text = &quot;List Files&quot; winDir = System.Environment.GetEnvironmentVariable(&quot;windir&quot;) 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 & &quot;\system.ini&quot;) 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(&quot;File is empty&quot;)

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 & &quot;\notepad.exe&quot;) With Me.ListBox1.Items .Clear .Add(&quot;File Name = &quot; & FileProps.FullName) .Add(&quot;Creation Time = &quot; & FileProps.CreationTime) .Add(&quot;Last Access Time = &quot; & FileProps.LastAccessTime) .Add(&quot;Last Write TIme = &quot; & FileProps.LastWriteTime) .Add(&quot;Size = &quot; & 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(&quot;c:\KBTest.txt&quot;) writer.WriteLine(&quot;File created using StreamWriter class.&quot;) writer.Close Me.ListBox1.Items.Clear Me.ListBox1.Items.Add(&quot;File Written to C:\KBTest.txt&quot;) 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

 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.</li></ol>

<div class="references_section">