Skip to main content This browser is no longer supported. Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support. Walkthrough: Manipulating Files and Directories in Visual Basic- Article
- 09/15/2021
- 10 minutes to read
In this articleThis 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. Visual Studio adds the project to Solution Explorer, and the Windows Forms Designer opens. Add the controls in the following table to the form, and set the corresponding values for their properties.
Control | Property | Value |
---|
ListBox
| Name
| filesListBox
| Button
| Name Text
| browseButton Browse
| Button
| Name Text
| examineButton Examine
| CheckBox
| Name Text
| saveCheckBox Save Results
| FolderBrowserDialog
| Name
| FolderBrowserDialog1
|
To select a folder, and list files in a folderCreate a Click event handler for browseButton by double-clicking the control on the form. The Code Editor opens. Add the following code to the Click event handler. If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
' List files in the folder.
ListFiles(FolderBrowserDialog1.SelectedPath)
End If
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. Add the following ListFiles method. Private Sub ListFiles(ByVal folderPath As String)
filesListBox.Items.Clear()
Dim fileNames = My.Computer.FileSystem.GetFiles(
folderPath, FileIO.SearchOption.SearchTopLevelOnly, "*.txt")
For Each fileName As String In fileNames
filesListBox.Items.Add(fileName)
Next
End Sub
This code first clears the ListBox. 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 fileCreate a Click event handler for examineButton by double-clicking the control on the form. Add the following code to the Click event handler. If filesListBox.SelectedItem Is Nothing Then
MessageBox.Show("Please select a file.")
Exit Sub
End If
' Obtain the file path from the list box selection.
Dim filePath = filesListBox.SelectedItem.ToString
' Verify that the file was not removed since the
' Browse button was clicked.
If My.Computer.FileSystem.FileExists(filePath) = False Then
MessageBox.Show("File Not Found: " & filePath)
Exit Sub
End If
' Obtain file information in a string.
Dim fileInfoText As String = GetTextForOutput(filePath)
' Show the file information.
MessageBox.Show(fileInfoText)
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. Add the following GetTextForOutput method. Private Function GetTextForOutput(ByVal filePath As String) As String
' Verify that the file exists.
If My.Computer.FileSystem.FileExists(filePath) = False Then
Throw New Exception("File Not Found: " & filePath)
End If
' Create a new StringBuilder, which is used
' to efficiently build strings.
Dim sb As New System.Text.StringBuilder()
' Obtain file information.
Dim thisFile As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(filePath)
' Add file attributes.
sb.Append("File: " & thisFile.FullName)
sb.Append(vbCrLf)
sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
sb.Append(vbCrLf)
sb.Append("Size: " & thisFile.Length.ToString & " bytes")
sb.Append(vbCrLf)
' Open the text file.
Dim sr As System.IO.StreamReader =
My.Computer.FileSystem.OpenTextFileReader(filePath)
' Add the first line from the file.
If sr.Peek() >= 0 Then
sb.Append("First Line: " & sr.ReadLine())
End If
sr.Close()
Return sb.ToString
End Function
The code uses the
GetFileInfo method to obtain file parameters. The file parameters are added to a StringBuilder. The
OpenTextFileReader method reads the file contents into a StreamReader. The first line of the contents is obtained from the StreamReader and is added to the StringBuilder . Run the application. Click
Browse, and browse to a folder that contains .txt files. Click OK. Select a file in the ListBox , and then click Examine. A MessageBox shows the file information. Stop running the application.
To add a log entryAdd the following code to the end of the examineButton_Click event handler. If saveCheckBox.Checked = True Then
' Place the log file in the same folder as the examined file.
Dim logFolder As String = My.Computer.FileSystem.GetFileInfo(filePath).DirectoryName
Dim logFilePath = My.Computer.FileSystem.CombinePath(logFolder, "log.txt")
Dim logText As String = "Logged: " & Date.Now.ToString &
vbCrLf & fileInfoText & vbCrLf & vbCrLf
' Append text to the log file.
My.Computer.FileSystem.WriteAllText(logFilePath, logText, append:=True)
End If
The code sets the log file path to put the log file in the same directory as that of
the selected file. The text of the log entry is set to the current date and time followed by the file information. The WriteAllText method, with the append argument set to True , is used to create the log entry. Run the application. Browse to a text file, select it in the ListBox , select the Save
Results check box, and then click Examine. Verify that the log entry is written to the log.txt file. Stop running the application.
To use the current directoryCreate an event handler for Form1_Load by double-clicking the form. Add the following code to the event handler. ' Set the default directory of the folder browser to the current directory.
FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.CurrentDirectory
This code sets the default directory of the folder browser to the current directory.
Run the application. When you click Browse the first time, the Browse For Folder dialog box opens to the current directory. Stop running the application.
To selectively enable controlsAdd the following SetEnabled method. Private Sub SetEnabled()
Dim anySelected As Boolean =
(filesListBox.SelectedItem IsNot Nothing)
examineButton.Enabled = anySelected
saveCheckBox.Enabled = anySelected
End Sub
The SetEnabled method enables or disables controls depending on whether an item is selected in the ListBox . Create a SelectedIndexChanged
event handler for filesListBox by double-clicking the ListBox control on the form. Add a call to SetEnabled in the new filesListBox_SelectedIndexChanged event handler. Add a call to SetEnabled at the end of the browseButton_Click event handler. Add a call to SetEnabled at the end of the Form1_Load event handler. Run the application. The Save Results check box and the Examine button are disabled if an item is not selected in the ListBox .
Full example using My.Computer.FileSystemFollowing is the complete example.
' This example uses members of the My.Computer.FileSystem
' object, which are available in Visual Basic.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Set the default directory of the folder browser to the current directory.
FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.CurrentDirectory
SetEnabled()
End Sub
Private Sub browseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles browseButton.Click
If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
' List files in the folder.
ListFiles(FolderBrowserDialog1.SelectedPath)
End If
SetEnabled()
End Sub
Private Sub ListFiles(ByVal folderPath As String)
filesListBox.Items.Clear()
Dim fileNames = My.Computer.FileSystem.GetFiles(
folderPath, FileIO.SearchOption.SearchTopLevelOnly, "*.txt")
For Each fileName As String In fileNames
filesListBox.Items.Add(fileName)
Next
End Sub
Private Sub examineButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles examineButton.Click
If filesListBox.SelectedItem Is Nothing Then
MessageBox.Show("Please select a file.")
Exit Sub
End If
' Obtain the file path from the list box selection.
Dim filePath = filesListBox.SelectedItem.ToString
' Verify that the file was not removed since the
' Browse button was clicked.
If My.Computer.FileSystem.FileExists(filePath) = False Then
MessageBox.Show("File Not Found: " & filePath)
Exit Sub
End If
' Obtain file information in a string.
Dim fileInfoText As String = GetTextForOutput(filePath)
' Show the file information.
MessageBox.Show(fileInfoText)
If saveCheckBox.Checked = True Then
' Place the log file in the same folder as the examined file.
Dim logFolder As String = My.Computer.FileSystem.GetFileInfo(filePath).DirectoryName
Dim logFilePath = My.Computer.FileSystem.CombinePath(logFolder, "log.txt")
Dim logText As String = "Logged: " & Date.Now.ToString &
vbCrLf & fileInfoText & vbCrLf & vbCrLf
' Append text to the log file.
My.Computer.FileSystem.WriteAllText(logFilePath, logText, append:=True)
End If
End Sub
Private Function GetTextForOutput(ByVal filePath As String) As String
' Verify that the file exists.
If My.Computer.FileSystem.FileExists(filePath) = False Then
Throw New Exception("File Not Found: " & filePath)
End If
' Create a new StringBuilder, which is used
' to efficiently build strings.
Dim sb As New System.Text.StringBuilder()
' Obtain file information.
Dim thisFile As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(filePath)
' Add file attributes.
sb.Append("File: " & thisFile.FullName)
sb.Append(vbCrLf)
sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
sb.Append(vbCrLf)
sb.Append("Size: " & thisFile.Length.ToString & " bytes")
sb.Append(vbCrLf)
' Open the text file.
Dim sr As System.IO.StreamReader =
My.Computer.FileSystem.OpenTextFileReader(filePath)
' Add the first line from the file.
If sr.Peek() >= 0 Then
sb.Append("First Line: " & sr.ReadLine())
End If
sr.Close()
Return sb.ToString
End Function
Private Sub filesListBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filesListBox.SelectedIndexChanged
SetEnabled()
End Sub
Private Sub SetEnabled()
Dim anySelected As Boolean =
(filesListBox.SelectedItem IsNot Nothing)
examineButton.Enabled = anySelected
saveCheckBox.Enabled = anySelected
End Sub
Full example using System.IOThe following equivalent example uses classes from the System.IO namespace instead of using My.Computer.FileSystem objects.
' This example uses classes from the System.IO namespace.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Set the default directory of the folder browser to the current directory.
FolderBrowserDialog1.SelectedPath =
System.IO.Directory.GetCurrentDirectory()
SetEnabled()
End Sub
Private Sub browseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles browseButton.Click
If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
' List files in the folder.
ListFiles(FolderBrowserDialog1.SelectedPath)
SetEnabled()
End If
End Sub
Private Sub ListFiles(ByVal folderPath As String)
filesListBox.Items.Clear()
Dim fileNames As String() =
System.IO.Directory.GetFiles(folderPath,
"*.txt", System.IO.SearchOption.TopDirectoryOnly)
For Each fileName As String In fileNames
filesListBox.Items.Add(fileName)
Next
End Sub
Private Sub examineButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles examineButton.Click
If filesListBox.SelectedItem Is Nothing Then
MessageBox.Show("Please select a file.")
Exit Sub
End If
' Obtain the file path from the list box selection.
Dim filePath = filesListBox.SelectedItem.ToString
' Verify that the file was not removed since the
' Browse button was clicked.
If System.IO.File.Exists(filePath) = False Then
MessageBox.Show("File Not Found: " & filePath)
Exit Sub
End If
' Obtain file information in a string.
Dim fileInfoText As String = GetTextForOutput(filePath)
' Show the file information.
MessageBox.Show(fileInfoText)
If saveCheckBox.Checked = True Then
' Place the log file in the same folder as the examined file.
Dim logFolder As String =
System.IO.Path.GetDirectoryName(filePath)
Dim logFilePath = System.IO.Path.Combine(logFolder, "log.txt")
' Append text to the log file.
Dim logText As String = "Logged: " & Date.Now.ToString &
vbCrLf & fileInfoText & vbCrLf & vbCrLf
System.IO.File.AppendAllText(logFilePath, logText)
End If
End Sub
Private Function GetTextForOutput(ByVal filePath As String) As String
' Verify that the file exists.
If System.IO.File.Exists(filePath) = False Then
Throw New Exception("File Not Found: " & filePath)
End If
' Create a new StringBuilder, which is used
' to efficiently build strings.
Dim sb As New System.Text.StringBuilder()
' Obtain file information.
Dim thisFile As New System.IO.FileInfo(filePath)
' Add file attributes.
sb.Append("File: " & thisFile.FullName)
sb.Append(vbCrLf)
sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
sb.Append(vbCrLf)
sb.Append("Size: " & thisFile.Length.ToString & " bytes")
sb.Append(vbCrLf)
' Open the text file.
Dim sr As System.IO.StreamReader =
System.IO.File.OpenText(filePath)
' Add the first line from the file.
If sr.Peek() >= 0 Then
sb.Append("First Line: " & sr.ReadLine())
End If
sr.Close()
Return sb.ToString
End Function
Private Sub filesListBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filesListBox.SelectedIndexChanged
SetEnabled()
End Sub
Private Sub SetEnabled()
Dim anySelected As Boolean =
(filesListBox.SelectedItem IsNot Nothing)
examineButton.Enabled = anySelected
saveCheckBox.Enabled = anySelected
End Sub
See also- System.IO
- FileSystem
- CurrentDirectory
- Walkthrough: Manipulating Files by Using .NET Framework Methods
FeedbackSubmit and view feedback for
When you click the folder in the navigation pane of the File Explorer window?
When you click a folder in the Navigation pane of the File Explorer window, you see its contents on the right side of the window in the File list. Windows 8 comes with several existing folders. In a window, the Address bar is located just above the title bar.
Which window is used to view and manage files and folders?
File Explorer (previously known as Windows Explorer) allows you to open, access, and rearrange your files and folders in Desktop view. If you've used prior versions of Windows before, File Explorer should feel like a familiar way to manage and organize your files.
How do you open a folder located on the desktop?
To open a folder on the desktop using a mouse, you should place the pointer or cursor of the mouse over the folder first. Then, without moving the mouse cursor, perform a double-click, meaning you have to click twice, in rapid succession, on the left mouse button.
What is files and folders in computer?
A file is the common storage unit in a computer, and all programs and data are "written" into a file and "read" from a file. A folder holds one or more files, and a folder can be empty until it is filled. A folder can also contain other folders, and there can be many levels of folders within folders.
|