0% found this document useful (0 votes)
15 views96 pages

Dotnet Visual Basic Developing Apps Programming Drives Directories Files

Uploaded by

Ponthep
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
15 views96 pages

Dotnet Visual Basic Developing Apps Programming Drives Directories Files

Uploaded by

Ponthep
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 96

Tell us about your PDF experience.

การประมวลผลไดรฟ์ , โฟลเดอร์, และไฟล์ (Visual Basic)


บทความ • 09/15/2021

คุณสามารถใช ้ Visual Basic เพือประมวลผลไดรฟ์ โฟลเดอร์ และไฟล์ด ้วยออบเจ็กต์


My.Computer.FileSystem ซงให ึ ิ ธิภาพทีดีกว่า และใชงานง่
้ประสท ้ ั วิธก
ายกว่าฟั งก์ชน ่
ี ารแบบเดิม เชน
FileOpenและ Write (แม ้ว่าจะยังใชงานได
้ ้ก็ตาม) สว่ นต่อไปนีจะกล่าวถึงวิธก
ี ารเหล่านีโดยละเอียด.

In This Section
การเข ้าถึงไฟล์ด ้วย Visual Basic
ออบเจ็กต์ My.Computer.FileSystem ทํางานกับไฟล์และโฟลเดอร์

พืนฐานของ .NET Framework File I/O และระบบไฟล์ (Visual Basic)


คําจํากัดความของสตรีม การดําเนินการสตรีม ประเภทของสตรีม การเข ้าถึงไฟล์และคุณสมบัต ิ
ิ ธิของไฟล์ การจัดเก็บไฟล์แบบแยก เหตุการณ์ของไฟล์
สท

ตัวอย่าง: การจัดการไฟล์ด ้วย .NET Framework


ี ารใช ้ .NET Framework จัดการไฟล์และโฟลเดอร์
วิธก

ตัวอย่าง: การจัดการไฟล์และโฟลเดอร์ใน Visual Basic


ออบเจ็กต์ My.Computer.FileSystem และคลาส System.IO

Related Sections
Program Structure and Code Conventions
Provides guidelines for the physical structure and appearance of programs.

FileSystem
Reference documentation for the My.Computer.FileSystem object and its members.
File Access with Visual Basic
Article • 09/15/2021

The My.Computer.FileSystem object provides tools for working with files and folders. Its
properties, methods, and events allow you to create, copy, move, investigate, and delete
files and folders. My.Computer.FileSystem provides better performance than the legacy
functions ( FileOpen , FileClose , Input , InputString , LineInput , etc.) that are provided
by Visual Basic for backward compatibility.

In This Section
Reading from Files
Lists topics dealing with using the My.Computer.FileSystem object to read from files

Writing to Files
Lists topics dealing with using the My.Computer.FileSystem object to write to files

Creating, Deleting, and Moving Files and Directories


Lists topics dealing with using the My.Computer.FileSystem object to creating, copying,
deleting and moving files and folders.

Parsing Text Files with the TextFieldParser Object


Discusses how to use the TextFieldReader to parse text files such as logs.

File Encodings
Describes file encodings and their use.

Walkthrough: Manipulating Files and Directories in Visual Basic


Demonstrates how to create a utility that reports information about files and folders.

Troubleshooting: Reading from and Writing to Text Files


Lists common problems encountered when reading and writing to text files, and
suggests remedies for each.
Reading from Files in Visual Basic
Article • 09/15/2021

This section explains how to perform tasks that are associated with reading from files.

In This Section
How to: Read from Text Files
Demonstrates how to read from a text file.

How to: Read From Comma-Delimited Text Files


Demonstrates how to read from a delimited text file.

How to: Read From Fixed-width Text Files


Demonstrates how to read from a fixed-width text file.

How to: Read From Text Files with Multiple Formats


Demonstrates how to read from a text file with multiple formats.

How to: Read From Binary Files


Demonstrates how to read from a binary file.

How to: Read Text from Files with a StreamReader


Demonstrates how to use a StreamReader to read from a file.

Reference
FileSystem
Describes the My.Computer.FileSystem object and its members.

ReadAllText
Describes the ReadAllText method.

ReadAllBytes
Describes the ReadAllBytes method.

OpenTextFieldParser
Describes the OpenTextFieldParser method.

OpenTextFileReader
Describes the OpenTextFileReader method.
Related Sections
Storing Data to and Reading from the Clipboard
Explains how to perform tasks that are associated with My.Computer.Clipboard , such as
reading data from or writing data to the Clipboard.

Parsing Text Files with the TextFieldParser Object


Provides an overview of reading text files with the TextFieldParser object.

Walkthrough: Manipulating Files and Directories in Visual Basic


Demonstrates how to use the My feature with files and directories.

Walkthrough: Manipulating Files by Using .NET Framework Methods


Demonstrates how to use .NET Framework methods with files and directories.
How to: Read From Text Files in Visual
Basic
Article • 09/15/2021

The ReadAllText method of the My.Computer.FileSystem object allows you to read from a
text file. The file encoding can be specified if the contents of the file use an encoding
such as ASCII or UTF-8.

If you are reading from a file with extended characters, you will need to specify the file
encoding.

7 Note

To read a file a single line of text at a time, use the OpenTextFileReader method of
the My.Computer.FileSystem object. The OpenTextFileReader method returns a
StreamReader object. You can use the ReadLine method of the StreamReader
object to read a file one line at a time. You can test for the end of the file using the
EndOfStream method of the StreamReader object.

To read from a text file


Use the ReadAllText method of the My.Computer.FileSystem object to read the contents
of a text file into a string, supplying the path. The following example reads the contents
of test.txt into a string and then displays it in a message box.

VB

Dim fileReader As String


fileReader = My.Computer.FileSystem.ReadAllText("C:\test.txt")
MsgBox(fileReader)

To read from a text file that is encoded


Use the ReadAllText method of the My.Computer.FileSystem object to read the contents
of a text file into a string, supplying the path and file encoding type. The following
example reads the contents of the UTF32 file test.txt into a string and then displays it in
a message box.
VB

Dim fileReader As String


fileReader = My.Computer.FileSystem.ReadAllText("C:\test.txt",
System.Text.Encoding.UTF32)
MsgBox(fileReader)

Robust Programming
The following conditions may cause an exception:

The path is not valid for one of the following reasons: it is a zero-length string, it
contains only white space, it contains invalid characters, or it is a device path
(ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

The file does not exist (FileNotFoundException).

The file is in use by another process or an I/O error occurs (IOException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or directory name in the path contains a colon (:) or is in an invalid format
(NotSupportedException).

There is not enough memory to write the string to buffer


(OutOfMemoryException).

The user lacks necessary permissions to view the path (SecurityException).

Do not make decisions about the contents of the file based on the name of the file. For
example, the file Form1.vb may not be a Visual Basic source file.

Verify all inputs before using the data in your application. The contents of the file may
not be what is expected, and methods to read from the file may fail.

See also
FileSystem
ReadAllText
Reading from Files
How to: Read From Comma-Delimited Text Files
How to: Read From Fixed-width Text Files
How to: Read From Text Files with Multiple Formats
Troubleshooting: Reading from and Writing to Text Files
Walkthrough: Manipulating Files and Directories in Visual Basic
File Encodings
How to: read from comma-delimited
text files in Visual Basic
Article • 09/15/2021

The TextFieldParser object provides a way to easily and efficiently parse structured text
files, such as logs. The TextFieldType property defines whether it is a delimited file or
one with fixed-width fields of text.

To parse a comma delimited text file


1. Create a new TextFieldParser . The following code creates the TextFieldParser
named MyReader and opens the file test.txt .

VB

Using MyReader As New Microsoft.VisualBasic.


FileIO.TextFieldParser(
"C:\TestFolder\test.txt")

2. Define the TextField type and delimiter. The following code defines the
TextFieldType property as Delimited and the delimiter as ",".

VB

MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")

3. Loop through the fields in the file. If any lines are corrupt, report an error and
continue parsing. The following code loops through the file, displaying each field
in turn and reporting any fields that are formatted incorrectly.

VB

Dim currentRow As String()


While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try

4. Close the While and Using blocks with End While and End Using .

VB

End While
End Using

Example
This example reads from the file test.txt .

VB

Using MyReader As New Microsoft.VisualBasic.


FileIO.TextFieldParser(
"C:\TestFolder\test.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try
End While
End Using

Robust programming
The following conditions may cause an exception:

A row cannot be parsed using the specified format (MalformedLineException). The


exception message specifies the line causing the exception, while the ErrorLine
property is assigned the text contained in the line.
The specified file does not exist (FileNotFoundException).

A partial-trust situation in which the user does not have sufficient permissions to
access the file. (SecurityException).

The path is too long (PathTooLongException).

The user does not have sufficient permissions to access the file
(UnauthorizedAccessException).

See also
Microsoft.VisualBasic.FileIO.TextFieldParser
How to: Read From Fixed-width Text Files
How to: Read From Text Files with Multiple Formats
Parsing Text Files with the TextFieldParser Object
Walkthrough: Manipulating Files and Directories in Visual Basic
Troubleshooting: Reading from and Writing to Text Files
How to: read from fixed-width text files
in Visual Basic
Article • 09/15/2021

The TextFieldParser object provides a way to easily and efficiently parse structured text
files, such as logs.

The TextFieldType property defines whether the parsed file is a delimited file or one
that has fixed-width fields of text. In a fixed-width text file, the field at the end can have
a variable width. To specify that the field at the end has a variable width, define it to
have a width less than or equal to zero.

To parse a fixed-width text file


1. Create a new TextFieldParser . The following code creates the TextFieldParser
named Reader and opens the file test.log .

VB

Using Reader As New Microsoft.VisualBasic.


FileIO.TextFieldParser("C:\TestFolder\test.log")

2. Define the TextFieldType property as FixedWidth , defining the width and format.
The following code defines the columns of text; the first is 5 characters wide, the
second 10, the third 11, and the fourth is of variable width.

VB

Reader.TextFieldType =
Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
Reader.SetFieldWidths(5, 10, 11, -1)

3. Loop through the fields in the file. If any lines are corrupted, report an error and
continue parsing.

VB

Dim currentRow As String()


While Not Reader.EndOfData
Try
currentRow = Reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try

4. Close the While and Using blocks with End While and End Using .

VB

End While
End Using

Example
This example reads from the file test.log .

VB

Using Reader As New Microsoft.VisualBasic.FileIO.


TextFieldParser("C:\TestFolder\test.log")

Reader.TextFieldType =
Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
Reader.SetFieldWidths(5, 10, 11, -1)
Dim currentRow As String()
While Not Reader.EndOfData
Try
currentRow = Reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try
End While
End Using

Robust programming
The following conditions may cause an exception:
A row cannot be parsed using the specified format (MalformedLineException). The
exception message specifies the line causing the exception, while the ErrorLine
property is assigned to the text contained in the line.

The specified file does not exist (FileNotFoundException).

A partial-trust situation in which the user does not have sufficient permissions to
access the file. (SecurityException).

The path is too long (PathTooLongException).

The user does not have sufficient permissions to access the file
(UnauthorizedAccessException).

See also
Microsoft.VisualBasic.FileIO.TextFieldParser
How to: Read From Comma-Delimited Text Files
How to: Read From Text Files with Multiple Formats
Parsing Text Files with the TextFieldParser Object
Walkthrough: Manipulating Files and Directories in Visual Basic
Troubleshooting: Reading from and Writing to Text Files
How to: Read from text files with
multiple formats in Visual Basic
Article • 04/12/2022

The TextFieldParser object provides a way to easily and efficiently parse structured text
files, such as logs. You can process a file with multiple formats by using the PeekChars
method to determine the format of each line as you parse through the file.

To parse a text file with multiple formats


1. Add a text file named testfile.txt to your project. Add the following content to the
text file:

text

Err 1001 Cannot access resource.


Err 2014 Resource not found.
Acc 10/03/2009User1 Administrator.
Err 0323 Warning: Invalid access attempt.
Acc 10/03/2009User2 Standard user.
Acc 10/04/2009User2 Standard user.

2. Define the expected format and the format used when an error is reported. The
last entry in each array is -1, therefore the last field is assumed to be of variable
width. This occurs when the last entry in the array is less than or equal to 0.

VB

Dim stdFormat As Integer() = {5, 10, 11, -1}


Dim errorFormat As Integer() = {5, 5, -1}

3. Create a new TextFieldParser object, defining the width and format.

VB

Using MyReader As New FileIO.TextFieldParser("..\..\testfile.txt")


MyReader.TextFieldType = FileIO.FieldType.FixedWidth
MyReader.FieldWidths = stdFormat

4. Loop through the rows, testing for format before reading.

VB
Dim currentRow As String()
While Not MyReader.EndOfData
Try
Dim rowType = MyReader.PeekChars(3)
If String.Compare(rowType, "Err") = 0 Then
' If this line describes an error, the format of the row
will be different.
MyReader.SetFieldWidths(errorFormat)
Else
' Otherwise parse the fields normally
MyReader.SetFieldWidths(stdFormat)
End If
currentRow = MyReader.ReadFields
For Each newString In currentRow
Console.Write(newString & "|")
Next
Console.WriteLine()

5. Write errors to the console.

VB

Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid.")
End Try
End While
End Using

Example
The following is the complete example that reads from the file testfile.txt :

VB

Dim stdFormat As Integer() = {5, 10, 11, -1}


Dim errorFormat As Integer() = {5, 5, -1}
Using MyReader As New FileIO.TextFieldParser("..\..\testfile.txt")
MyReader.TextFieldType = FileIO.FieldType.FixedWidth
MyReader.FieldWidths = stdFormat
Dim currentRow As String()
While Not MyReader.EndOfData
Try
Dim rowType = MyReader.PeekChars(3)
If String.Compare(rowType, "Err") = 0 Then
' If this line describes an error, the format of the row
will be different.
MyReader.SetFieldWidths(errorFormat)
Else
' Otherwise parse the fields normally
MyReader.SetFieldWidths(stdFormat)
End If
currentRow = MyReader.ReadFields
For Each newString In currentRow
Console.Write(newString & "|")
Next
Console.WriteLine()
Catch ex As FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using
Console.ReadLine()

Robust programming
The following conditions may cause an exception:

A row cannot be parsed using the specified format (MalformedLineException). The


exception message specifies the line causing the exception, while the ErrorLine
property is assigned to the text contained in the line.
The specified file does not exist (FileNotFoundException).
A partial-trust situation in which the user does not have sufficient permissions to
access the file. (SecurityException).
The path is too long (PathTooLongException).
The user does not have sufficient permissions to access the file
(UnauthorizedAccessException).

See also
Microsoft.VisualBasic.FileIO.TextFieldParser
PeekChars
MalformedLineException
WriteAllText
EndOfData
TextFieldType
How to: Read From Comma-Delimited Text Files
How to: Read From Fixed-width Text Files
Parsing Text Files with the TextFieldParser Object
How to: Read From Binary Files in Visual
Basic
Article • 09/15/2021

The My.Computer.FileSystem object provides the ReadAllBytes method for reading from
binary files.

To read from a binary file


Use the ReadAllBytes method, which returns the contents of a file as a byte array.
This example reads from the file C:/Documents and Settings/selfportrait.jpg .

VB

Dim bytes = My.Computer.FileSystem.ReadAllBytes(


"C:/Documents and Settings/selfportrait.jpg")
PictureBox1.Image = Image.FromStream(New IO.MemoryStream(bytes))

For large binary files, you can use the Read method of the FileStream object to
read from the file only a specified amount at a time. You can then limit how much
of the file is loaded into memory for each read operation. The following code
example copies a file and allows the caller to specify how much of the file is read
into memory per read operation.

VB

' This method does not trap for exceptions. If an exception is


' encountered opening the file to be copied or writing to the
' destination location, then the exception will be thrown to
' the requestor.
Public Sub CopyBinaryFile(ByVal path As String,
ByVal copyPath As String,
ByVal bufferSize As Integer,
ByVal overwrite As Boolean)

Dim inputFile = IO.File.Open(path, IO.FileMode.Open)

If overwrite AndAlso My.Computer.FileSystem.FileExists(copyPath)


Then
My.Computer.FileSystem.DeleteFile(copyPath)
End If

' Adjust array length for VB array declaration.


Dim bytes = New Byte(bufferSize - 1) {}
While inputFile.Read(bytes, 0, bufferSize) > 0
My.Computer.FileSystem.WriteAllBytes(copyPath, bytes, True)
End While

inputFile.Close()
End Sub

Robust Programming
The following conditions may cause an exception to be thrown:

The path is not valid for one of the following reasons: it is a zero-length string, it
contains only white space, it contains invalid characters, or it is a device path
(ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

The file does not exist (FileNotFoundException).

The file is in use by another process, or an I/O error occurs (IOException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or directory name in the path contains a colon (:) or is in an invalid format
(NotSupportedException).

There is not enough memory to write the string to buffer


(OutOfMemoryException).

The user lacks necessary permissions to view the path (SecurityException).

Do not make decisions about the contents of the file based on the name of the file. For
example, the file Form1.vb may not be a Visual Basic source file.

Verify all inputs before using the data in your application. The contents of the file may
not be what is expected, and methods to read from the file may fail.

See also
ReadAllBytes
WriteAllBytes
Reading from Files
How to: Read From Text Files with Multiple Formats
Storing Data to and Reading from the Clipboard
How to: Read Text from Files with a
StreamReader (Visual Basic)
Article • 09/15/2021

The My.Computer.FileSystem object provides methods to open a TextReader and a


TextWriter. These methods, OpenTextFileWriter and OpenTextFileReader , are advanced
methods that do not appear in IntelliSense unless you select the All tab.

To read a line from a file with a text reader


Use the OpenTextFileReader method to open the TextReader, specifying the file.
This example opens the file named testfile.txt , reads a line from it, and displays
the line in a message box.

VB

Dim fileReader As System.IO.StreamReader


fileReader =
My.Computer.FileSystem.OpenTextFileReader("C:\\testfile.txt")
Dim stringReader As String
stringReader = fileReader.ReadLine()
MsgBox("The first line of the file is " & stringReader)

Robust Programming
The file that is read must be a text file.

Do not make decisions about the contents of the file based on the name of the file. For
example, the file Form1.vb may not be a Visual Basic source file.

Verify all inputs before using the data in your application. The contents of the file may
not be what is expected, and methods to read from the file may fail.

.NET Framework Security


To read from a file, your assembly requires a privilege level granted by the
FileIOPermission class. If you are running in a partial-trust context, the code might throw
an exception due to insufficient privileges. For more information, see Code Access
Security Basics. The user also needs access to the file. For more information, see ACL
Technology Overview.
See also
FileSystem
OpenFileDialog
OpenTextFileWriter
OpenTextFileReader
SaveFileDialog Component
Reading from Files
Writing to Files in Visual Basic
Article • 09/15/2021

This section explains how to perform tasks that involve writing to files.

In This Section
How to: Write Text to Files
Demonstrates how to write to text files.

How to: Append to Text Files


Demonstrates how to append text to a text file.

How to: Write to Binary Files


Demonstrates how to write to a binary file.

How to: Write Text to Files in the My Documents Directory


Demonstrates how to create and write to a new text file in the My Documents directory.

How to: Write Text to Files with a StreamWriter


Demonstrates how to write to a file with a System.IO.StreamWriter object.

Reference
FileSystem
Describes the My.Computer.FileSystem object and its methods and properties.

OpenTextFileWriter
Describes the OpenTextFileWriter method.

WriteAllBytes
Describes the WriteAllBytes method.

WriteAllText
Describes the WriteAllText method.

Related Sections
Reading from Files
Explains how to perform tasks that involve reading from files.
Creating, Deleting, and Moving Files and Directories
Explains how to perform tasks that involve creating, deleting, moving, and renaming
files and directories.

Storing Data to and Reading from the Clipboard


Explains how to perform tasks that are associated with My.Computer.Clipboard , such as
reading data from or writing data to the Clipboard.

File Encodings
Provides an overview of file encodings.
How to: Write Text to Files in Visual
Basic
Article • 09/15/2021

The WriteAllText method can be used to write text to files. If the specified file does not
exist, it is created.

Procedure

To write text to a file

Use the WriteAllText method to write text to a file, specifying the file and text to
be written. This example writes the line "This is new text." to the file named
test.txt , appending the text to any existing text in the file.

VB

My.Computer.FileSystem.WriteAllText("C:\TestFolder1\test.txt",
"This is new text to be added.", True)

To write a series of strings to a file


Loop through the string collection. Use the WriteAllText method to write text to a
file, specifying the target file and string to be added and setting append to True .

This example writes the names of the files in the Documents and Settings directory
to FileList.txt , inserting a carriage return between each for better readability.

VB

For Each foundFile As String In


My.Computer.FileSystem.GetFiles("C:\Documents and Settings")
foundFile = foundFile & vbCrLf
My.Computer.FileSystem.WriteAllText(
"C:\Documents and Settings\FileList.txt", foundFile, True)
Next

Robust Programming
The following conditions may cause an exception:

The path is not valid for one of the following reasons: it is a zero-length string, it
contains only white space, it contains invalid characters, or it is a device path (starts
with \\.\) (ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

File points to a path that does not exist (FileNotFoundException or

DirectoryNotFoundException).

The file is in use by another process, or an I/O error occurs (IOException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or directory name in the path contains a colon (:) or is in an invalid format
(NotSupportedException).

The user lacks necessary permissions to view the path (SecurityException).

The disk is full, and the call to WriteAllText fails (IOException).

If you are running in a partial-trust context, the code might throw an exception due to
insufficient privileges. For more information, see Code Access Security Basics.

See also
FileSystem
WriteAllText
How to: Read from Text Files
How to: Append to Text Files in Visual
Basic
Article • 09/15/2021

The WriteAllText method can be used to append to a text file by specifying that the
append parameter is set to True .

To append to a text file


Use the WriteAllText method, specifying the target file and string to be appended
and setting the append parameter to True .

This example writes the string "This is a test string." to the file named
Testfile.txt .

VB

Dim inputString As String = "This is a test string."


My.Computer.FileSystem.WriteAllText(
"C://testfile.txt", inputString, True)

Robust Programming
The following conditions may cause an exception:

The path is not valid for one of the following reasons: it is a zero-length string, it
contains only white space, it contains invalid characters, or it is a device path (starts
with \\.\) (ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

File points to a path that does not exist (FileNotFoundException or


DirectoryNotFoundException).

The file is in use by another process, or an I/O error occurs (IOException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or directory name in the path contains a colon (:) or is in an invalid format
(NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).

See also
WriteAllText
FileSystem
Writing to Files
How to: Write to Binary Files in Visual
Basic
Article • 09/15/2021

The WriteAllBytes method writes data to a binary file. If the append parameter is True , it
will append the data to the file; otherwise data in the file is overwritten.

If the specified path excluding the file name is not valid, a DirectoryNotFoundException
exception will be thrown. If the path is valid but the file does not exist, the file will be
created.

To write to a binary file


Use the WriteAllBytes method, supplying the file path and name and the bytes to be
written. This example appends the data array CustomerData to the file named
CollectedData.dat .

VB

Dim CustomerData As Byte() = (From c In customerQuery).ToArray()

My.Computer.FileSystem.WriteAllBytes(
"C:\MyDocuments\CustomerData", CustomerData, True)

Robust Programming
The following conditions may create an exception:

The path is not valid for one of the following reasons: it is a zero-length string; it
contains only white space; or it contains invalid characters. (ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

File points to a path that does not exist (FileNotFoundException or


DirectoryNotFoundException).

The file is in use by another process, or an I/O error occurs (IOException).

The path exceeds the system-defined maximum length (PathTooLongException).


A file or directory name in the path contains a colon (:) or is in an invalid format
(NotSupportedException).

The user lacks necessary permissions to view the path (SecurityException).

See also
WriteAllBytes
How to: Write Text to Files
How to: Write Text to Files in the My
Documents Directory in Visual Basic
Article • 09/15/2021

The My.Computer.FileSystem.SpecialDirectories object allows you to access special


directories, such as the MyDocuments directory.

Procedure

To write new text files in the My Documents directory

1. Use the My.Computer.FileSystem.SpecialDirectories.MyDocuments property to


supply the path.

VB

Dim filePath As String


filePath = System.IO.Path.Combine(
My.Computer.FileSystem.SpecialDirectories.MyDocuments, "test.txt")

2. Use the WriteAllText method to write text to the specified file.

VB

My.Computer.FileSystem.WriteAllText(filePath, "some text", True)

Example
VB

Try
Dim filePath As String
filePath = System.IO.Path.Combine(
My.Computer.FileSystem.SpecialDirectories.MyDocuments,
"test.txt")
My.Computer.FileSystem.WriteAllText(filePath, "some text", False)
Catch fileException As Exception
Throw fileException
End Try
Compiling the Code
Replace test.txt with the name of the file you want to write to.

Robust Programming
This code rethrows all the exceptions that may occur when writing text to the file. You
can reduce the likelihood of exceptions by using Windows Forms controls such as the
OpenFileDialog and the SaveFileDialog components that limit the user choices to valid
file names. Using these controls is not foolproof, however. The file system can change
between the time the user selects a file and the time that the code executes. Exception
handling is therefore nearly always necessary when with working with files.

.NET Framework Security


If you are running in a partial-trust context, the code might throw an exception due to
insufficient privileges. For more information, see Code Access Security Basics.

This example creates a new file. If an application needs to create a file, that application
needs Create permission for the folder. Permissions are set using access control lists. If
the file already exists, the application needs only Write permission, a lesser privilege.
Where possible, it is more secure to create the file during deployment, and only grant
Read privileges to a single file, rather than to grant Create privileges for a folder. Also, it
is more secure to write data to user folders than to the root folder or the Program Files
folder. For more information, see ACL Technology Overview.

See also
Path.Combine
Computer
FileSystem
WriteAllText
SpecialDirectories
How to: Write Text to Files with a
StreamWriter in Visual Basic
Article • 09/15/2021

This example opens a StreamWriter object with the


My.Computer.FileSystem.OpenTextFileWriter method and uses it to write a string to a

text file with the WriteLine method of the StreamWriter class.

Example
VB

Dim file As System.IO.StreamWriter


file = My.Computer.FileSystem.OpenTextFileWriter("c:\test.txt", True)
file.WriteLine("Here is the first string.")
file.Close()

Robust Programming
The following conditions may cause an exception:

The file exists and is read-only (IOException).

The disk is full (IOException).

The pathname is too long (PathTooLongException).

.NET Framework Security


This example creates a new file, if the file does not already exist. If an application needs
to create a file, that application needs Create access for the folder. If the file already
exists, the application needs only Write access, a lesser privilege. Where possible, it is
more secure to create the file during deployment, and only grant Read access to a single
file, rather than Create access for a folder.

See also
StreamWriter
OpenTextFileWriter
How to: Read from Text Files
Writing to Files
Creating, Deleting, and Moving Files
and Directories in Visual Basic
Article • 09/15/2021

This section lists tasks associated with creating, deleting, moving, and renaming files and
directories in Visual Basic.

In This Section
How to: Copy Files with a Specific Pattern to a Directory
Demonstrates how to copy files with a specific file name pattern, such as only .txt files,
to a directory.

How to: Create a Copy of a File in the Same Directory


Demonstrates how to create a copy of a file in the same directory.

How to: Create a Copy of a File in a Different Directory


Demonstrates how to copy a file to another directory.

How to: Create a File


Demonstrates how to create a file.

How to: Delete a File


Demonstrates how to delete a file.

How to: Find Files with a Specific Pattern


Demonstrates how to list only files with a specific file name pattern in a directory.

How to: Move a File


Demonstrates how to move a file to a different directory.

How to: Rename a File


Demonstrates how to rename a file.

How to: Copy a Directory to Another Directory


Demonstrates how to copy a directory to another location.

How to: Create a Directory


Demonstrates how to create a directory.

How to: Find Subdirectories with a Specific Pattern


Demonstrates how to list directories with a specific pattern in their name.
How to: Get the Collection of Files in a Directory
Demonstrates how to list the files in a directory.

How to: Retrieve the Contents of the My Documents Directory


Demonstrates how to read from special directories.

How to: Parse File Paths


Demonstrates how to use My methods to combine file paths.

Reference
FileSystem
Describes the My.Computer.FileSystem object and its members.

CombinePath
Describes the CombinePath method.

CopyDirectory
Describes the CopyDirectory method.

CopyFile
Describes the CopyFile method.

CreateDirectory
Describes the CreateDirectory method.

DeleteDirectory
Describes the DeleteDirectory method.

DeleteFile
Describes the DeleteFile method.

GetParentPath
Describes the GetParentPath method.

MoveDirectory
Describes the MoveDirectory method.

MoveFile
Describes the MoveFile method.

RenameDirectory
Describes the RenameDirectory method.
RenameFile
Describes the RenameFile method.

SpecialDirectories
Describes the SpecialDirectories object.

Related Sections
Reading from Files
Lists tasks associated with reading from files.

Writing to Files
Lists tasks involving writing to files.
How to: Copy Files with a Specific
Pattern to a Directory in Visual Basic
Article • 09/15/2021

The GetFiles method returns a read-only collection of strings representing the path
names for the files. You can use the wildCards parameter to specify a specific pattern.

An empty collection is returned if no matching files are found.

You can use the CopyFile method to copy the files to a directory.

To copy files with a specific pattern to a directory


1. Use the GetFiles method to return the list of files. This example returns all .rtf files
in the specified directory.

VB

For Each foundFile As String In My.Computer.FileSystem.GetFiles(


My.Computer.FileSystem.SpecialDirectories.MyDocuments,
Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly,
"*.rtf")

2. Use the CopyFile method to copy the files. This example copies the files to the
directory named testdirectory .

VB

My.Computer.FileSystem.CopyFile(foundFile, "C:\testdirectory\" &


My.Computer.FileSystem.GetName(foundFile))

3. Close the For statement with a Next statement.

VB

Next

Example
The following example, which presents the above snippets in complete form, copies all
.rtf files in the specified directory to the directory named testdirectory .

VB

For Each foundFile As String In My.Computer.FileSystem.GetFiles(


My.Computer.FileSystem.SpecialDirectories.MyDocuments,
Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, "*.rtf")

My.Computer.FileSystem.CopyFile(foundFile, "C:\testdirectory\" &


foundFile)
Next

.NET Framework Security


The following conditions may cause an exception:

The path is not valid for one of the following reasons: it is a zero-length string, it
contains only white space, it contains invalid characters, or it is a device path (starts
with \\.\) (ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

The directory does not exist (DirectoryNotFoundException).

The directory points to an existing file (IOException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or directory name in the path contains a colon (:) or is in an invalid format
(NotSupportedException).

The user lacks necessary permissions to view the path (SecurityException). The user
lacks necessary permissions (UnauthorizedAccessException).

See also
CopyFile
GetFiles
How to: Find Subdirectories with a Specific Pattern
Troubleshooting: Reading from and Writing to Text Files
How to: Get the Collection of Files in a Directory
How to: Create a Copy of a File in the
Same Directory in Visual Basic
Article • 09/15/2021

Use the My.Computer.FileSystem.CopyFile method to copy files. The parameters allow


you to overwrite existing files, rename the file, show the progress of the operation, and
allow the user to cancel the operation.

To create a copy of a file in the same folder


Use the CopyFile method, supplying the target file and the location. The following
example creates a copy of test.txt called test2.txt .

VB

My.Computer.FileSystem.CopyFile("C:\TestFolder\test.txt",
"C:\TestFolder\test2.txt",
Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs,
FileIO.UICancelOption.DoNothing)

To create a copy of a file in the same folder, overwriting


existing files
Use the CopyFile method, supplying the target file and location, and setting
overwrite to True . The following example creates a copy of test.txt called

test2.txt and overwrites any existing files by that name.

VB

My.Computer.FileSystem.CopyFile("C:\TestFolder\test.txt",
"C:\TestFolder\test2.txt", True)

Robust Programming
The following conditions may cause an exception to be thrown:

The path is not valid for one of the following reasons: it is a zero-length string, it
contains only white space, it contains invalid characters, or it is a device path (starts
with \\.\) (ArgumentException).
The system could not retrieve the absolute path (ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

The source file is not valid or does not exist (FileNotFoundException).

The combined path points to an existing directory (IOException).

The destination file exists and overwrite is set to False (IOException).

The user does not have sufficient permissions to access the file (IOException).

A file in the target folder with the same name is in use (IOException).

A file or folder name in the path contains a colon (:) or is in an invalid format
(NotSupportedException).

ShowUI is set to True , onUserCancel is set to ThrowException , and the user has

cancelled the operation (OperationCanceledException).

ShowUI is set to True , onUserCancel is set to ThrowException , and an unspecified


I/O error occurs (OperationCanceledException).

The path exceeds the system-defined maximum length (PathTooLongException).

The user does not have required permission (UnauthorizedAccessException).

The user lacks necessary permissions to view the path (SecurityException).

See also
FileSystem
CopyFile
UICancelOption
How to: Copy Files with a Specific Pattern to a Directory
How to: Create a Copy of a File in a Different Directory
How to: Copy a Directory to Another Directory
How to: Rename a File
How to: Create a Copy of a File in a
Different Directory in Visual Basic
Article • 09/15/2021

The My.Computer.FileSystem.CopyFile method allows you to copy files. Its parameters


provide the ability to overwrite existing files, rename the file, show the progress of the
operation, and allow the user to cancel the operation.

To copy a text file to another folder


Use the CopyFile method to copy a file, specifying a source file and the target
directory. The overwrite parameter allows you to specify whether or not to
overwrite existing files. The following code examples demonstrate how to use
CopyFile .

VB

' Copy the file to a new location without overwriting existing file.
My.Computer.FileSystem.CopyFile(
"C:\UserFiles\TestFiles\testFile.txt",
"C:\UserFiles\TestFiles2\testFile.txt")

' Copy the file to a new folder, overwriting existing file.


My.Computer.FileSystem.CopyFile(
"C:\UserFiles\TestFiles\testFile.txt",
"C:\UserFiles\TestFiles2\testFile.txt",
Microsoft.VisualBasic.FileIO.UIOption.AllDialogs,
Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)

' Copy the file to a new folder and rename it.


My.Computer.FileSystem.CopyFile(
"C:\UserFiles\TestFiles\testFile.txt",
"C:\UserFiles\TestFiles2\NewFile.txt",
Microsoft.VisualBasic.FileIO.UIOption.AllDialogs,
Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)

Robust Programming
The following conditions may cause an exception to be thrown:

The path is not valid for one of the following reasons: it is a zero-length string, it
contains only white space, it contains invalid characters, or it is a device path (starts
with \\.\) (ArgumentException).
The system could not retrieve the absolute path (ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

The source file is not valid or does not exist (FileNotFoundException).

The combined path points to an existing directory (IOException).

The destination file exists and overwrite is set to False (IOException).

The user does not have sufficient permissions to access the file (IOException).

A file in the target folder with the same name is in use (IOException).

A file or folder name in the path contains a colon (:) or is in an invalid format
(NotSupportedException).

ShowUI is set to True , onUserCancel is set to ThrowException , and the user has

cancelled the operation (OperationCanceledException).

ShowUI is set to True , onUserCancel is set to ThrowException , and an unspecified


I/O error occurs (OperationCanceledException).

The path exceeds the system-defined maximum length (PathTooLongException).

The user does not have required permission (UnauthorizedAccessException).

The user lacks necessary permissions to view the path (SecurityException).

See also
FileSystem
CopyFile
UICancelOption
How to: Copy Files with a Specific Pattern to a Directory
How to: Create a Copy of a File in the Same Directory
How to: Copy a Directory to Another Directory
How to: Rename a File
How to: Create a File in Visual Basic
Article • 05/26/2022

This example creates an empty text file at the specified path using the Create method in
the File class.

Example
VB

Imports System.IO
Imports System.Text

Module Module1

Sub Main()
Dim path As String = "c:\temp\MyTest.txt"

' Create or overwrite the file.


Dim fs As FileStream = File.Create(path)

' Add text to the file.


Dim info As Byte() = New UTF8Encoding(True).GetBytes("This is some
text in the file.")
fs.Write(info, 0, info.Length)
fs.Close()
End Sub

End Module

Compiling the Code


Use the file variable to write to the file.

Robust Programming
If the file already exists, it is replaced.

The following conditions may cause an exception:

The path name is malformed. For example, it contains illegal characters or is only
white space (ArgumentException).

The path is read-only (IOException).


The path name is Nothing (ArgumentNullException).

The path name is too long (PathTooLongException).

The path is invalid (DirectoryNotFoundException).

The path is only a colon ":" (NotSupportedException).

.NET Framework Security


A SecurityException may be thrown in partial-trust environments.

The call to the Create method requires FileIOPermission.

An UnauthorizedAccessException is thrown if the user does not have permission to


create the file.

See also
System.IO
Create
How to: Delete a File in Visual Basic
Article • 09/15/2021

The DeleteFile method of the My.Computer.FileSystem object allows you to delete a


file. Among the options it offers are: whether to send the deleted file to the Recycle Bin,
whether to ask the user to confirm that the file should be deleted, and what to do when
the user cancels the operation.

To delete a text file


Use the DeleteFile method to delete the file. The following code demonstrates
how to delete the file named test.txt .

VB

My.Computer.FileSystem.DeleteFile("C:\test.txt")

To delete a text file and ask the user to confirm that the
file should be deleted
Use the DeleteFile method to delete the file, setting showUI to AllDialogs . The
following code demonstrates how to delete the file named test.txt and allow the
user to confirm that the file should be deleted.

VB

My.Computer.FileSystem.DeleteFile("C:\test.txt",
Microsoft.VisualBasic.FileIO.UIOption.AllDialogs,
Microsoft.VisualBasic.FileIO.RecycleOption.DeletePermanently,
Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)

To delete a text file and send it to the Recycle Bin


Use the DeleteFile method to delete the file, specifying SendToRecycleBin for the
recycle parameter. The following code demonstrates how to delete the file named

test.txt and send it to the Recycle Bin.

VB
My.Computer.FileSystem.DeleteFile("C:\test.txt",
Microsoft.VisualBasic.FileIO.UIOption.AllDialogs,
Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin)

Robust Programming
The following conditions may cause an exception:

The path is not valid for one of the following reasons: it is a zero-length string, it
contains only white space, it contains invalid characters, or it is a device path (starts
with \\.\) (ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or folder name in the path contains a colon (:) or is in an invalid format
(NotSupportedException).

The file is in use (IOException).

The user lacks necessary permissions to view the path (SecurityException).

The file does not exist (FileNotFoundException).

The user does not have permission to delete the file, or the file is read-only
(UnauthorizedAccessException).

A partial-trust situation exists in which the user does not have sufficient
permissions (SecurityException).

The user cancelled the operation and onUserCancel is set to ThrowException


(OperationCanceledException).

See also
UICancelOption
FileSystem
UIOption
RecycleOption
How to: Get the Collection of Files in a Directory
How to: Find Files with a Specific
Pattern in Visual Basic
Article • 09/15/2021

The GetFiles method returns a read-only collection of strings representing the path
names for the files. You can use the wildCards parameter to specify a specific pattern. If
you would like to include subdirectories in the search, set the searchType parameter to
SearchOption.SearchAllSubDirectories .

An empty collection is returned if no files matching the specified pattern are found.

7 Note

For information about returning a file list by using the DirectoryInfo class of the
System.IO namespace, see GetFiles.

To find files with a specified pattern


Use the GetFiles method, supplying the name and path of the directory you want
to search and specifying the pattern. The following example returns all files with
the extension .dll in the directory and adds them to ListBox1 .

VB

For Each foundFile As String In My.Computer.FileSystem.GetFiles(


My.Computer.FileSystem.SpecialDirectories.MyDocuments,
Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories,
"*.dll")

Listbox1.Items.Add(foundFile)
Next

.NET Framework Security


The following conditions may cause an exception:

The path is not valid for one of the following reasons: it is a zero-length string, it
contains only white space, it contains invalid characters, or it is a device path (starts
with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).

directory does not exist (DirectoryNotFoundException).

directory points to an existing file (IOException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or folder name in the path contains a colon (:) or is in an invalid format
(NotSupportedException).

The user lacks necessary permissions to view the path (SecurityException).

The user lacks necessary permissions (UnauthorizedAccessException).

See also
GetFiles
How to: Find Subdirectories with a Specific Pattern
Troubleshooting: Reading from and Writing to Text Files
How to: Get the Collection of Files in a Directory
How to: Move a File in Visual Basic
Article • 09/15/2021

The My.Computer.FileSystem.MoveFile method can be used to move a file to another


folder. If the target structure does not exist, it will be created.

To move a file
Use the MoveFile method to move the file, specifying the file name and location
for both the source file and the target file. This example moves the file named
test.txt from TestDir1 to TestDir2 . Note that the target file name is specified

even though it is the same as the source file name.

VB

My.Computer.FileSystem.MoveFile("C:\TestDir1\test.txt",
"C:\TestDir2\test.txt")

To move a file and rename it


Use the MoveFile method to move the file, specifying the source file name and
location, the target location, and the new name at the target location. This example
moves the file named test.txt from TestDir1 to TestDir2 and renames it
nexttest.txt .

VB

My.Computer.FileSystem.MoveFile("C:\TestDir1\test.txt",
"C:\TestDir2\nexttest.txt",
FileIO.UIOption.AllDialogs,
FileIO.UICancelOption.ThrowException)

Robust Programming
The following conditions may cause an exception:

The path is not valid for one of the following reasons: it is a zero-length string, it
contains only white space, it contains invalid characters, or it is a device path (starts
with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).

destinationFileName is Nothing or an empty string (ArgumentNullException).

The source file is not valid or does not exist (FileNotFoundException).

The combined path points to an existing directory, the destination file exists and
overwrite is set to False , a file in the target directory with the same name is in

use, or the user does not have sufficient permissions to access the file
(IOException).

A file or directory name in the path contains a colon (:) or is in an invalid format
(NotSupportedException).

showUI is set to True , onUserCancel is set to ThrowException , and either the user

has cancelled the operation or an unspecified I/O error occurs


(OperationCanceledException).

The path exceeds the system-defined maximum length (PathTooLongException).

The user lacks necessary permissions to view the path (SecurityException).

The user does not have required permission (UnauthorizedAccessException).

See also
MoveFile
How to: Rename a File
How to: Create a Copy of a File in a Different Directory
How to: Parse File Paths
How to: Rename a File in Visual Basic
Article • 09/15/2021

Use the RenameFile method of the My.Computer.FileSystem object to rename a file by


supplying the current location, file name, and the new file name. This method cannot be
used to move a file; use the MoveFile method to move and rename the file.

To rename a file
Use the My.Computer.FileSystem.RenameFile method to rename a file. This example
renames the file named Test.txt to SecondTest.txt .

VB

' Change "c:\test.txt" to the path and filename for the file that
' you want to rename.
My.Computer.FileSystem.RenameFile("C:\Test.txt", "SecondTest.txt")

This code example is also available as an IntelliSense code snippet. In the code snippet
picker, the snippet is located in File system - Processing Drives, Folders, and Files. For
more information, see Code Snippets.

Robust Programming
The following conditions may cause an exception:

The path is not valid for one of the following reasons: it is a zero-length string, it
contains only white space, it contains invalid characters, or it is a device path (starts
with \\.\) (ArgumentException).

newName contains path information (ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

newName is Nothing or an empty string (ArgumentNullException).

The source file is not valid or does not exist (FileNotFoundException).

There is an existing file or directory with the name specified in newName


(IOException).

The path exceeds the system-defined maximum length (PathTooLongException).


A file or directory name in the path contains a colon (:) or is in an invalid format
(NotSupportedException).

The user lacks necessary permissions to view the path (SecurityException).

The user does not have the required permission (UnauthorizedAccessException).

See also
RenameFile
How to: Move a File
Creating, Deleting, and Moving Files and Directories
How to: Create a Copy of a File in the Same Directory
How to: Create a Copy of a File in a Different Directory
How to: Copy a Directory to Another
Directory in Visual Basic
Article • 09/15/2021

Use the CopyDirectory method to copy a directory to another directory. This method
copies the contents of the directory as well as the directory itself. If the target directory
does not exist, it will be created. If a directory with the same name exists in the target
location and overwrite is set to False , the contents of the two directories will be
merged. You can specify a new name for the directory during the operation.

When copying files within a directory, exceptions may be thrown that are caused by
specific file, such as a file existing during a merge while overwrite is set to False . When
such exceptions are thrown, they are consolidated into a single exception, whose Data
property holds entries in which the file or directory path is the key and the specific
exception message is contained in the corresponding value.

To copy a directory to another directory


Use the CopyDirectory method, specifying source and destination directory names.
The following example copies the directory named TestDirectory1 into
TestDirectory2 , overwriting existing files.

VB

My.Computer.FileSystem.CopyDirectory("C:\TestDirectory1",
"C:\TestDirectory2", True)

This code example is also available as an IntelliSense code snippet. In the code
snippet picker, it is located in File system - Processing Drives, Folders, and Files.
For more information, see Code Snippets.

Robust Programming
The following conditions may cause an exception:

The new name specified for the directory contains a colon (:) or slash (\ or /)
(ArgumentException).
The path is not valid for one of the following reasons: it is a zero-length string, it
contains only white space, it contains invalid characters, or it is a device path (starts
with \\.\) (ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

destinationDirectoryName is Nothing or an empty string (ArgumentNullException)

The source directory does not exist (DirectoryNotFoundException).

The source directory is a root directory (IOException).

The combined path points to an existing file (IOException).

The source path and target path are the same (IOException).

ShowUI is set to UIOption.AllDialogs and the user cancels the operation, or one or

more files in the directory cannot be copied (OperationCanceledException).

The operation is cyclic (InvalidOperationException).

The path contains a colon (:) (NotSupportedException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or folder name in the path contains a colon (:) or is in an invalid format
(NotSupportedException).

The user lacks necessary permissions to view the path (SecurityException).

A destination file exists but cannot be accessed (UnauthorizedAccessException).

See also
CopyDirectory
How to: Find Subdirectories with a Specific Pattern
How to: Get the Collection of Files in a Directory
How to: Create a Directory in Visual
Basic
Article • 09/15/2021

Use the CreateDirectory method of the My.Computer.FileSystem object to create


directories.

If the directory already exists, no exception is thrown.

To create a directory
Use the CreateDirectory method by specifying the full path of the location where
the directory should be created. This example creates the directory NewDirectory
in C:\Documents and Settings\All Users\Documents .

VB

My.Computer.FileSystem.CreateDirectory(
"C:\Documents and Settings\All Users\Documents\NewDirectory")

Robust Programming
The following conditions may cause an exception:

The directory name is malformed. For example, it contains illegal characters or is


only white space (ArgumentException).

The parent directory of the directory to be created is read-only (IOException).

The directory name is Nothing (ArgumentNullException).

The directory name is too long (PathTooLongException).

The directory name is a colon ":" (NotSupportedException).

The user does not have permission to create the directory


(UnauthorizedAccessException).

The user lacks permissions in a partial-trust situation (SecurityException).

See also
CreateDirectory
Creating, Deleting, and Moving Files and Directories
How to: Find Subdirectories with a
Specific Pattern in Visual Basic
Article • 09/15/2021

The GetDirectories method returns a read-only collection of strings representing the


path names for the subdirectories in a directory. You can use the wildCards parameter
to specify a specific pattern. If you would like to include the contents of subdirectories in
the search, set the searchType parameter to SearchOption.SearchAllSubDirectories .

An empty collection is returned if no directories matching the specified pattern are


found.

To find subdirectories with a specific pattern


Use the GetDirectories method, supplying the name and path of the directory you
want to search. The following example returns all the directories in the directory
structure that contain the word "Logs" in their name, and adds them to ListBox1 .

VB

For Each foundDirectory As String In


My.Computer.FileSystem.GetDirectories(
My.Computer.FileSystem.SpecialDirectories.MyDocuments,
FileIO.SearchOption.SearchTopLevelOnly,
"*Logs*")

ListBox1.Items.Add(foundDirectory)
Next

Robust Programming
The following conditions may cause an exception:

The path is not valid for one of the following reasons: it is a zero-length string, it
contains only white space, it contains invalid characters, or it is a device path (starts
with \\.\) (ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

One or more of the specified wildcard characters is Nothing , an empty string, or


contains only spaces (ArgumentNullException).
directory does not exist (DirectoryNotFoundException).

directory points to an existing file (IOException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or folder name in the path contains a colon (:) or is in an invalid format
(NotSupportedException).

The user lacks necessary permissions to view the path (SecurityException).

The user lacks necessary permissions (UnauthorizedAccessException).

See also
GetDirectories
How to: Find Files with a Specific Pattern
How to: Get the Collection of Files in a
Directory in Visual Basic
Article • 09/15/2021

The overloads of the FileSystem.GetFiles method return a read-only collection of strings


representing the names of the files within a directory:

Use the GetFiles(String) overload for a simple file search in a specified directory,
without searching subdirectories.

Use the GetFiles(String, SearchOption, String[]) overload to specify additional


options for your search. You can use the wildCards parameter to specify a search
pattern. To include subdirectories in the search, set the searchType parameter to
SearchOption.SearchAllSubDirectories.

An empty collection is returned if no files matching the specified pattern are found.

To list files in a directory


Use one of the FileSystem.GetFiles method overloads, supplying the name and
path of the directory to search in the directory parameter. The following example
returns all files in the directory and adds them to ListBox1 .

VB

For Each foundFile As String In My.Computer.FileSystem.GetFiles(


My.Computer.FileSystem.SpecialDirectories.MyDocuments)

listBox1.Items.Add(foundFile)
Next

Robust Programming
The following conditions may cause an exception:

The path is not valid for one of the following reasons: it is a zero-length string, it
contains only white space, it contains invalid characters, or it is a device path (starts
with \\.\) (ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).


directory does not exist (DirectoryNotFoundException).

directory points to an existing file (IOException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or directory name in the path contains a colon (:) or is in an invalid format
(NotSupportedException).

The user lacks necessary permissions to view the path (SecurityException).

The user lacks necessary permissions (UnauthorizedAccessException).

See also
GetFiles
How to: Find Files with a Specific Pattern
How to: Find Subdirectories with a Specific Pattern
How to: Retrieve the Contents of the My
Documents Directory in Visual Basic
Article • 09/15/2021

The SpecialDirectories object can be used to read from many of the All Users
directories, such as My Documents or Desktop.

To read from the My Documents folder


Use the ReadAllText method to read the text from each file in a specific directory.
The following code specifies a directory and file and then uses ReadAllText to read
them into the string named patients .

VB

Dim path As String


Dim patients As String
path = My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\" &
"Patients.txt"
patients = My.Computer.FileSystem.ReadAllText(path)

See also
SpecialDirectories
ReadAllText
How to: Parse File Paths in Visual Basic
Article • 09/15/2021

The FileSystem object offers a number of useful methods when parsing file paths.

The CombinePath method takes two paths and returns a properly formatted
combined path.

The GetParentPath method returns the absolute path of the parent of the provided
path.

The GetFileInfo method returns a FileInfo object that can be queried to determine
the file's properties, such as its name and path.

Do not make decisions about the contents of the file based on the file name extension.
For example, the file Form1.vb may not be a Visual Basic source file.

To determine a file's name and path


Use the DirectoryName and Name properties of the FileInfo object to determine a
file's name and path. This example determines the name and path and displays
them.

VB

Dim testFile As System.IO.FileInfo


testFile =
My.Computer.FileSystem.GetFileInfo("C:\TestFolder1\test1.txt")
Dim folderPath As String = testFile.DirectoryName
MsgBox(folderPath)
Dim fileName As String = testFile.Name
MsgBox(fileName)

To combine a file's name and directory to create the full


path
Use the CombinePath method, supplying the directory and name. This example
takes the strings folderPath and fileName created in the previous example,
combines them, and displays the result.

VB
Dim fullPath As String
fullPath = My.Computer.FileSystem.CombinePath(folderPath, fileName)
MsgBox(fullPath)

See also
FileSystem
CombinePath
FileInfo
GetFileInfo
How to: Get the Collection of Files in a Directory
Parsing text files with the
TextFieldParser object (Visual Basic)
Article • 09/15/2021

The TextFieldParser object allows you to parse and process very large file that are
structured as delimited-width columns of text, such as log files or legacy database
information. Parsing a text file with TextFieldParser is similar to iterating over a text file,
while the parse method to extract fields of text is similar to string manipulation methods
used to tokenize delimited strings.

Parsing different types of text files


Text files may have fields of various width, delimited by a character such as a comma or
a tab space. Define TextFieldType and the delimiter, as in the following example, which
uses the SetDelimiters method to define a tab-delimited text file:

VB

testReader.SetDelimiters(vbTab)

Other text files may have field widths that are fixed. In such cases, you need to define
the TextFieldType as FixedWidth and define the widths of each field, as in the following
example. This example uses the SetFieldWidths method to define the columns of text:
the first column is 5 characters wide, the second is 10, the third is 11, and the fourth is of
variable width.

VB

testReader.SetFieldWidths(5, 10, 11, -1)


testReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.FixedWidth

Once the format is defined, you can loop through the file, using the ReadFields method
to process each line in turn.

If a field does not match the specified format, a MalformedLineException exception is


thrown. When such exceptions are thrown, the ErrorLine and ErrorLineNumber
properties hold the text causing the exception and the line number of that text.

Parsing files with multiple formats


The PeekChars method of the TextFieldParser object can be used to check each field
before reading it, allowing you to define multiple formats for the fields and react
accordingly. For more information, see How to: Read From Text Files with Multiple
Formats.

See also
OpenTextFieldParser
TextFieldParser
PeekChars
ReadFields
CommentTokens
Delimiters
ErrorLine
ErrorLineNumber
FieldWidths
HasFieldsEnclosedInQuotes
LineNumber
TextFieldType
TrimWhiteSpace
SetDelimiters
SetFieldWidths
File Encodings (Visual Basic)
Article • 09/15/2021

File encodings, also known as character encodings, specify how to represent characters
when text processing. One encoding may be preferable over another in terms of which
language characters it can or cannot handle, although Unicode is usually preferred.

When reading from or writing to files, improperly matching file encodings may result in
exceptions or incorrect results.

Types of Encodings
Unicode is the preferred encoding when working with files. Unicode is a worldwide
character-encoding standard that uses 16-bit code values to represent all the characters
used in modern computing, including technical symbols and special characters used in
publishing.

Previous character-encoding standards consisted of traditional character sets, such as


the Windows ANSI character set that uses 8-bit code values, or combinations of 8-bit
values, to represent the characters used in a specific language or geographical region.

Encoding Class
The Encoding class represents a character encoding. This table lists the type of
encodings available and describes each.

Name Description

ASCIIEncoding Represents an ASCII character encoding of Unicode characters.

UnicodeEncoding Represents a UTF-16 encoding of Unicode characters.

UTF32Encoding Represents a UTF-32 encoding of Unicode characters.

UTF7Encoding Represents a UTF-7 encoding of Unicode characters.

UTF8Encoding Represents a UTF-8 encoding of Unicode characters.

See also
Reading from Files
Writing to Files
Troubleshooting: reading from and
writing to text files (Visual Basic)
Article • 09/15/2021

This topic discusses common problems encountered when working with text files and
suggests an approach to each.

Common problems
The most common issues encountered when working with text files include security
exceptions, file encodings, or invalid paths.

Security exceptions
A SecurityException is thrown when a security error occurs. This is often a result of the
user lacking necessary permissions, which may be solved by adding permissions or
working with files in isolated storage.

File encodings
File encodings, also known as character encodings, specify how to represent characters
when text processing. Unexpected characters in a text file may result from incorrect
encoding. For most files, one encoding may be preferable over another in terms of
which language characters it can or cannot handle, although Unicode is usually
preferred. For more information, see File Encodings and Encoding.

Incorrect paths
When parsing file paths, particularly relative paths, it is easy to supply the wrong data.
Many problems can be corrected by making sure you are supplying the correct path. For
more information, see How to: Parse File Paths.

See also
FileSystem
Reading from Files
Writing to Files
Parsing Text Files with the TextFieldParser Object
Basics of .NET Framework File I/O and
the File System (Visual Basic)
Article • 09/15/2021

Classes in the System.IO namespace are used to work with drives, files, and directories.

The System.IO namespace contains the File and Directory classes, which provide the
.NET Framework functionality that manipulates files and directories. Because the
methods of these objects are static or shared members, you can use them directly
without creating an instance of the class first. Associated with these classes are the
FileInfo and DirectoryInfo classes, which will be familiar to users of the My feature. To
use these classes, you must fully qualify the names or import the appropriate
namespaces by including the Imports statement(s) at the beginning of the affected
code. For more information, see Imports Statement (.NET Namespace and Type).

7 Note

Other topics in this section use the My.Computer.FileSystem object instead of


System.IO classes to work with drives, files, and directories. The

My.Computer.FileSystem object is intended primarily for use in Visual Basic

programs. System.IO classes are intended for use by any language that supports
the .NET Framework, including Visual Basic.

Definition of a Stream
The .NET Framework uses streams to support reading from and writing to files. You can
think of a stream as a one-dimensional set of contiguous data, which has a beginning
and an end, and where the cursor indicates the current position in the stream.
Stream Operations
The data contained in the stream may come from memory, a file, or a TCP/IP socket.
Streams have fundamental operations that can be applied to them:

Reading. You can read from a stream, transferring data from the stream into a data
structure, such as a string or an array of bytes.

Writing. You can write to a stream, transferring data from a data source into the
stream.

Seeking. You can query and modify your position in the stream.

For more information, see Composing Streams.

Types of Streams
In the .NET Framework, a stream is represented by the Stream class, which forms the
abstract class for all other streams. You cannot directly create an instance of the Stream
class, but must use one of the classes it implements.

There are many types of streams, but for the purposes of working with file input/output
(I/O), the most important types are the FileStream class, which provides a way to read
from and write to files, and the IsolatedStorageFileStream class, which provides a way to
create files and directories in isolated storage. Other streams that can be used when
working with file I/O include:

BufferedStream

CryptoStream

MemoryStream

NetworkStream.

The following table lists tasks commonly accomplished with a stream:

To See

Read and write to a data file How to: Read and Write to a Newly Created Data File

Read text from a file How to: Read Text from a File

Write text to a file How to: Write Text to a File

Read characters from a string How to: Read Characters from a String
To See

Write characters to a string How to: Write Characters to a String

Encrypt data Encrypting Data

Decrypt data Decrypting Data

File Access and Attributes


You can control how files are created, opened, and shared with the FileAccess, FileMode,
and FileShare enumerations, which contain the flags used by the constructors of the
FileStream class. For example, when you open or create a new FileStream, the FileMode
enumeration allows you to specify whether the file is opened for appending, whether a
new file is created if the specified file does not exist, whether the file is overwritten, and
so forth.

The FileAttributes enumeration enables the gathering of file-specific information. The


FileAttributes enumeration returns the file's stored attributes, such as whether it is
compressed, encrypted, hidden, read-only, an archive, a directory, a system file, or a
temporary file.

The following table lists tasks involving file access and file attributes:

To See

Open and append text to a log file How to: Open and Append to a Log File

Determine the attributes of a file FileAttributes

File Permissions
Controlling access to files and directories can be done with the FileIOPermission class.
This may be particularly important for developers working with Web Forms, which by
default run within the context of a special local user account named ASPNET, which is
created as part of the ASP.NET and .NET Framework installations. When such an
application requests access to a resource, the ASPNET user account has limited
permissions, which may prevent the user from performing actions such as writing to a
file from a Web application. For more information, see FileIOPermission.

Isolated File Storage


Isolated storage is an attempt to solve problems created when working with files where
the user or code may lack necessary permissions. Isolated storage assigns each user a
data compartment, which can hold one or more stores. Stores can be isolated from each
other by user and by assembly. Only the user and assembly that created a store have
access to it. A store acts as a complete virtual file system—within one store you can
create and manipulate directories and files.

The following table lists tasks commonly associated with isolated file storage.

To See

Create an isolated store How to: Obtain Stores for Isolated Storage

Enumerate isolated stores How to: Enumerate Stores for Isolated Storage

Delete an isolated store How to: Delete Stores in Isolated Storage

Create a file or directory in isolated How to: Create Files and Directories in Isolated
storage Storage

Find a file in isolated storage How to: Find Existing Files and Directories in Isolated
Storage

Read from or write to a file in isolated How to: Read and Write to Files in Isolated Storage
storage

Delete a file or directory in isolated How to: Delete Files and Directories in Isolated
storage Storage

File Events
The FileSystemWatcher component allows you to watch for changes in files and
directories on your system or on any computer to which you have network access. For
example, if a file is modified, you might want to send a user an alert that the change has
taken place. When changes occur, one or more events are raised, stored in a buffer, and
handed to the FileSystemWatcher component for processing.

See also
Composing Streams
File and Stream I/O
Asynchronous File I/O
Classes Used in .NET Framework File I/O and the File System (Visual Basic)
Classes Used in .NET Framework File I/O
and the File System (Visual Basic)
Article • 09/15/2021

The following tables list the classes commonly used for .NET Framework file I/O,
categorized into file I/O classes, classes used for creating streams, and classes used to
read and write to streams.

For a more comprehensive listing, see Class Library Overview.

Basic I/O Classes for Files, Drives, and


Directories
The following table lists and describes the main classes used for file I/O.

Class Description

System.IO.Directory Provides static methods for creating, moving, and


enumerating through directories and
subdirectories.

System.IO.DirectoryInfo Provides instance methods for creating, moving,


and enumerating through directories and
subdirectories.

System.IO.DriveInfo Provides instance methods for creating, moving,


and enumerating through drives.

System.IO.File Provides static methods for creating, copying,


deleting, moving, and opening files, and aids in
the creation of a FileStream .

System.IO.FileAccess Defines constants for read, write, or read/write


access to a file.

System.IO.FileAttributes Provides attributes for files and directories such as


Archive , Hidden , and ReadOnly .

System.IO.FileInfo Provides static methods for creating, copying,


deleting, moving, and opening files, and aids in
the creation of a FileStream .
Class Description

System.IO.FileMode Controls how a file is opened. This parameter is


specified in many of the constructors for
FileStream and IsolatedStorageFileStream , and
for the Open methods of File and FileInfo.

System.IO.FileShare Defines constants for controlling the type of


access other file streams can have to the same file.

System.IO.Path Provides methods and properties for processing


directory strings.

System.Security.Permissions.FileIOPermission Controls the access of files and folders by defining


Read, Write, Append and PathDiscovery
permissions.

Classes Used to Create Streams


The following table lists and describes the main classes used to create streams.

Class Description

System.IO.BufferedStream Adds a buffering layer to read and write operations


on another stream.

System.IO.FileStream Supports random access to files through its Seek


method. FileStream opens files synchronously by
default but also supports asynchronous operation.

System.IO.MemoryStream Creates a stream whose backing store is memory,


rather than a file.

System.Net.Sockets.NetworkStream Provides the underlying stream of data for network


access.

System.Security.Cryptography.CryptoStream Defines a stream that links data streams to


cryptographic transformations.

Classes Used to Read from and Write to


Streams
The following table shows the specific classes used for reading from and writing to files
with streams.
Class Description

System.IO.BinaryReader Reads encoded strings and primitive data types from a FileStream.

System.IO.BinaryWriter Writes encoded strings and primitive data types to a FileStream.

System.IO.StreamReader Reads characters from a FileStream, using CurrentEncoding to convert


characters to and from bytes. StreamReader has a constructor that
attempts to ascertain the correct CurrentEncoding for a given stream,
based on the presence of a CurrentEncoding-specific preamble, such
as a byte order mark.

System.IO.StreamWriter Writes characters to a FileStream , using Encoding to convert


characters to bytes.

System.IO.StringReader Reads characters from a String . Output can be either a stream in any
encoding or a String .

System.IO.StringWriter Writes characters to a String . Output can be either a stream in any


encoding or a String .

See also
Composing Streams
File and Stream I/O
Asynchronous File I/O
Basics of .NET Framework File I/O and the File System (Visual Basic)
Walkthrough: Manipulating Files by
Using .NET Framework Methods (Visual
Basic)
Article • 09/15/2021

This walkthrough demonstrates how to open and read a file using the StreamReader
class, check to see if a file is being accessed, search for a string within a file read with an
instance of the StreamReader class, and write to a file using the StreamWriter class.

7 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.

Creating the Application


Start Visual Studio and begin the project by creating a form that the user can use to
write to the designated file.

To create the project


1. On the File menu, select New Project.

2. In the New Project pane, click Windows Application.

3. In the Name box type MyDiary and click OK.

Visual Studio adds the project to Solution Explorer, and the Windows Forms
Designer opens.

4. Add the controls in the following table to the form and set the corresponding
values for their properties.

Object Properties Value


Object Properties Value

Button Name Submit

Text Submit Entry

Button Name Clear

Text Clear Entry

TextBox Name Entry

Text Please enter something.

Multiline False

Writing to the File


To add the ability to write to a file via the application, use the StreamWriter class.
StreamWriter is designed for character output in a particular encoding, whereas the
Stream class is designed for byte input and output. Use StreamWriter for writing lines of
information to a standard text file. For more information on the StreamWriter class, see
StreamWriter.

To add writing functionality


1. From the View menu, choose Code to open the Code Editor.

2. Because the application references the System.IO namespace, add the following
statements at the very beginning of your code, before the class declaration for the
form, which begins Public Class Form1 .

VB

Imports System.IO

Before writing to the file, you must create an instance of a StreamWriter class.

3. From the View menu, choose Designer to return to the Windows Forms Designer.
Double-click the Submit button to create a Click event handler for the button, and
then add the following code.

VB
Dim fw As StreamWriter

7 Note

The Visual Studio Integrated Development Environment (IDE) will return to the
Code Editor and position the insertion point within the event handler where you
should add the code.

1. To write to the file, use the Write method of the StreamWriter class. Add the
following code directly after Dim fw As StreamWriter . You do not need to worry
that an exception will be thrown if the file is not found, because it will be created if
it does not already exist.

VB

Dim ReadString As String


Try
'Pass the file path and name to the StreamWriter constructor.
'Indicate that Append is True, so file will not be overwritten.
fw = New StreamWriter("C:\MyDiary.txt", True)
ReadString = Entry.Text
fw.WriteLine(ReadString)
Finally
'Close the file.
fw.Close()
End Try

2. Make sure that the user cannot submit a blank entry by adding the following code
directly after Dim ReadString As String .

VB

If (Entry.Text = "" Or Entry.Text = "Please enter something.") Then


Entry.Text = "Please enter something."
Return
End If

3. Because this is a diary, the user will want to assign a date to each entry. Insert the
following code after fw = New StreamWriter("C:\MyDiary.txt", True) to set the
variable Today to the current date.

VB
Dim Today As DateTime
Today = Now
fw.Write(CStr(Today))
fw.Write(ControlChars.CrLf)

4. Finally, attach code to clear the TextBox. Add the following code to the Clear
button's Click event.

VB

Entry.Text = ""

Adding Display Features to the Diary


In this section, you add a feature that displays the latest entry in the
DisplayEntry TextBox. You can also add a ComboBox that displays various entries and

from which a user can select an entry to display in the DisplayEntry TextBox. An instance
of the StreamReader class reads from MyDiary.txt . Like the StreamWriter class,
StreamReader is intended for use with text files.

For this section of the walkthrough, add the controls in the following table to the form
and set the corresponding values for their properties.

Control Properties Values

TextBox Name DisplayEntry

Visible False

Size 120,60

Multiline True

Button Name Display

Text Display

Button Name GetEntries

Text Get Entries


Control Properties Values

ComboBox Name PickEntries

Text Select an Entry

Enabled False

To populate the combo box


1. The PickEntries ComboBox is used to display the dates on which a user submits
each entry, so the user can select an entry from a specific date. Create a Click event
handler to the GetEntries button and add the following code.

VB

Dim fr As StreamReader = Nothing


Dim FileString As String
FileString = ""
Try
fr = New System.IO.StreamReader("C:\MyDiary.txt")
PickEntries.Items.Clear()
PickEntries.Enabled = True
Do
FileString = fr.ReadLine
If IsDate(FileString) Then
PickEntries.Items.Add(FileString)
End If
Loop Until (FileString Is Nothing)
Finally
If fr IsNot Nothing Then
fr.Close()
End If
End Try
PickEntries.Enabled = True

2. To test your code, press F5 to compile the application, and then click Get Entries.
Click the drop-down arrow in the ComboBox to display the entry dates.

To choose and display individual entries


1. Create a Click event handler for the Display button and add the following code.

VB

Dim fr As StreamReader
Dim ReadString As String
'Make sure ReadString begins empty.
ReadString = ""
Dim FileString As String
fr = New StreamReader("C:\MyDiary.txt")
'If no entry has been selected, show the whole file.
If PickEntries.Enabled = False Or PickEntries.SelectedText Is Nothing
Then
Do
'Read a line from the file into FileString.
FileString = fr.ReadLine
'add it to ReadString
ReadString = ReadString & ControlChars.CrLf & FileString
Loop Until (FileString = Nothing)
Else
'An entry has been selected, find the line that matches.
Do

FileString = fr.ReadLine
Loop Until FileString = CStr(PickEntries.SelectedItem)
FileString = CStr(PickEntries.SelectedItem) & ControlChars.CrLf
ReadString = FileString & fr.ReadLine

'Read from the file until EOF or another Date is found.


Do Until ((fr.Peek < 0) Or (IsDate(fr.ReadLine)))
ReadString = ReadString & fr.ReadLine
Loop
End If
fr.Close()
DisplayEntry.Visible = True
DisplayEntry.Text = ReadString

2. To test your code, press F5 to compile the application, and then submit an entry.
Click Get Entries, select an entry from the ComboBox, and then click Display. The
contents of the selected entry appear in the DisplayEntry TextBox.

Enabling Users to Delete or Modify Entries


Finally, you can include additional functionality enables users to delete or modify an
entry by using DeleteEntry and EditEntry buttons. Both buttons remain disabled
unless an entry is displayed.

Add the controls in the following table to the form and set the corresponding values for
their properties.

Control Properties Values


Control Properties Values

Button Name DeleteEntry

Text Delete Entry

Enabled False

Button Name EditEntry

Text Edit Entry

Enabled False

Button Name SubmitEdit

Text Submit Edit

Enabled False

To enable deletion and modification of entries


1. Add the following code to the Display button's Click event, after
DisplayEntry.Text = ReadString .

VB

DeleteEntry.enabled = True

2. Create a Click event handler for the DeleteEntry button and add the following
code.

VB

Dim fr As StreamReader
Dim ReadString As String
Dim WriteString As String
Dim ConfirmDelete As MsgBoxResult
fr = New StreamReader("C:\MyDiary.txt")
ReadString = fr.ReadLine
' Read through the textfile
Do Until (fr.Peek < 0)
ReadString = ReadString & vbCrLf & fr.ReadLine
Loop
WriteString = Replace(ReadString, DisplayEntry.Text, "")
fr.Close()
' Check to make sure the user wishes to delete the entry
ConfirmDelete = MsgBox("Do you really wish to delete this entry?",
MsgBoxStyle.OKCancel)
If ConfirmDelete = MsgBoxResult.OK Then
File.Delete("C:\MyDiary.txt")
Dim fw As StreamWriter = File.CreateText("C:\MyDiary.txt")
fw.WriteLine(WriteString)
fw.Close()
' Reset controls on the form
DisplayEntry.Text = ""
PickEntries.Text = ""
PickEntries.Items.Clear()
PickEntries.Enabled = False
DeleteEntry.Enabled = False
End If

3. When a user displays an entry, the EditEntry button becomes enabled. Add the
following code to the Click event of the Display button after DisplayEntry.Text =
ReadString .

VB

EditEntry.Enabled = True

4. Create a Click event handler for the EditEntry button and add the following code.

VB

Entry.Text = DisplayEntry.Text
SubmitEdit.Enabled = True

5. Create a Click event handler for the SubmitEdit button and add the following code

VB

Dim fr As StreamReader
Dim ReadString As String
Dim WriteString As String
If Entry.Text = "" Then
MsgBox("Use Delete to Delete an Entry")
Return
End If
fr = New StreamReader("C:\MyDiary.txt")
ReadString = fr.ReadLine
Do Until (fr.Peek < 0)
ReadString = ReadString & vbCrLf & fr.ReadLine
Loop
WriteString = Replace(ReadString, DisplayEntry.Text, Entry.Text)
fr.Close()
File.Delete("C:\MyDiary.txt")
Dim fw As StreamWriter = File.CreateText("C:\MyDiary.txt")
fw.WriteLine(WriteString)
fw.Close()
DisplayEntry.Text = Entry.Text
Entry.Text = ""
EditEntry.Enabled = False
SubmitEdit.Enabled = False

To test your code, press F5 to compile the application. Click Get Entries, select an entry,
and then click Display. The entry appears in the DisplayEntry TextBox. Click Edit Entry.
The entry appears in the Entry TextBox. Edit the entry in the Entry TextBox and click
Submit Edit. Open the MyDiary.txt file to confirm your correction. Now select an entry
and click Delete Entry. When the MessageBox requests confirmation, click OK. Close the
application and open MyDiary.txt to confirm the deletion.

See also
StreamReader
StreamWriter
Walkthroughs
Walkthrough: Manipulating Files and
Directories in Visual Basic
Article • 09/15/2021

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.

7 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


1. On the File menu, click New Project.

The New Project dialog box appears.

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

3. 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.

4. Add the controls in the following table to the form, and set the corresponding
values for their properties.

Control Property Value

ListBox Name filesListBox


Control Property Value

Button Name browseButton

Text Browse

Button Name examineButton

Text Examine

CheckBox Name saveCheckBox

Text Save Results

FolderBrowserDialog Name FolderBrowserDialog1

To select a folder, and list files in a folder


1. Create a Click event handler for browseButton by double-clicking the control on
the form. The Code Editor opens.

2. Add the following code to the Click event handler.

VB

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.

3. Add the following ListFiles method.

VB

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.

4. 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.

5. Stop running the application.

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


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

2. Add the following code to the Click event handler.

VB

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.

3. Add the following GetTextForOutput method.

VB

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 .

4. 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.

5. Stop running the application.

To add a log entry


1. Add the following code to the end of the examineButton_Click event handler.

VB

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.

2. 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.
3. Stop running the application.

To use the current directory


1. Create an event handler for Form1_Load by double-clicking the form.

2. Add the following code to the event handler.

VB

' 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.

3. Run the application. When you click Browse the first time, the Browse For Folder
dialog box opens to the current directory.

4. Stop running the application.

To selectively enable controls


1. Add the following SetEnabled method.

VB

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 .

2. Create a SelectedIndexChanged event handler for filesListBox by double-clicking


the ListBox control on the form.

3. Add a call to SetEnabled in the new filesListBox_SelectedIndexChanged event


handler.
4. Add a call to SetEnabled at the end of the browseButton_Click event handler.

5. Add a call to SetEnabled at the end of the Form1_Load event handler.

6. 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.FileSystem


Following is the complete example.

VB

' 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.IO


The following equivalent example uses classes from the System.IO namespace instead of
using My.Computer.FileSystem objects.

VB

' 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

You might also like