This walkthrough provides an introduction to the fundamentals of file I/O in Visual Basic. It describes how to create a small application that lists and examines text files in a directory. For each selected text file, the application provides file attributes and the first line of content. There is an option to write information to a log file.

This walkthrough uses members of the My.Computer.FileSystem Object, which are available in Visual Basic. See FileSystem for more information. At the end of the walkthrough, an equivalent example is provided that uses classes from the System.IO namespace.

Note

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Personalizing the IDE.

To create the project

On the File menu, click New Project.

The New Project dialog box appears.

In the Installed Templates pane, expand Visual Basic, and then click Windows. In the Templates pane in the middle, click Windows Forms Application.

In the Name box, type FileExplorer to set the project name, and then click OK.

The FolderBrowserDialog1.ShowDialog call opens the Browse For Folder dialog box. After the user clicks OK, the SelectedPath property is sent as an argument to the ListFiles method, which is added in the next step.

The GetFiles method then retrieves a collection of strings, one for each file in the directory. The GetFiles method accepts a search pattern argument to retrieve files that match a particular pattern. In this example, only files that have the extension .txt are returned.

The strings that are returned by the GetFiles method are then added to the ListBox.

Run the application. Click the Browse button. In the Browse For Folder dialog box, browse to a folder that contains .txt files, and then select the folder and click OK.

The ListBox contains a list of .txt files in the selected folder.

Stop running the application.

To obtain attributes of a file, and content from a text file

Create a Click event handler for examineButton by double-clicking the control on the form.

The code verifies that an item is selected in the ListBox. It then obtains the file path entry from the ListBox. The FileExists method is used to check whether the file still exists.

The file path is sent as an argument to the GetTextForOutput method, which is added in the next step. This method returns a string that contains file information. The file information appears in a MessageBox.