Dotnet Visual Basic Developing Apps Programming Drives Directories Files
Dotnet Visual Basic Developing Apps Programming Drives Directories Files
In This Section
การเข ้าถึงไฟล์ด ้วย Visual Basic
ออบเจ็กต์ My.Computer.FileSystem ทํางานกับไฟล์และโฟลเดอร์
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
File Encodings
Describes file encodings and their use.
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.
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.
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.
VB
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).
A file or directory name in the path contains a colon (:) or is in an invalid format
(NotSupportedException).
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.
VB
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
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
Robust programming
The following conditions may cause an exception:
A partial-trust situation in which the user does not have sufficient permissions to
access the file. (SecurityException).
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.
VB
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
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
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.
A partial-trust situation in which the user does not have sufficient permissions to
access the file. (SecurityException).
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.
text
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
VB
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()
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
Robust programming
The following conditions may cause an exception:
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.
VB
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
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).
A file or directory name in the path contains a colon (:) or is in an invalid format
(NotSupportedException).
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
VB
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.
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.
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.
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
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)
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
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).
DirectoryNotFoundException).
A file or directory name in the path contains a colon (:) or is in an invalid format
(NotSupportedException).
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 .
This example writes the string "This is a test string." to the file named
Testfile.txt .
VB
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).
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.
VB
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).
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
Procedure
VB
VB
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.
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
Example
VB
Robust Programming
The following conditions may cause an exception:
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.
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.
You can use the CopyFile method to copy the files to a directory.
VB
2. Use the CopyFile method to copy the files. This example copies the files to the
directory named testdirectory .
VB
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
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).
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
VB
My.Computer.FileSystem.CopyFile("C:\TestFolder\test.txt",
"C:\TestFolder\test2.txt",
Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs,
FileIO.UICancelOption.DoNothing)
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 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
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
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")
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 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
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"
End Module
Robust Programming
If the file already exists, it is replaced.
The path name is malformed. For example, it contains illegal characters or is only
white space (ArgumentException).
See also
System.IO
Create
How to: Delete a File in Visual Basic
Article • 09/15/2021
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)
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).
A file or folder name in the path contains a colon (:) or is in an invalid format
(NotSupportedException).
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).
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.
VB
Listbox1.Items.Add(foundFile)
Next
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).
A file or folder name in the path contains a colon (:) or is in an invalid format
(NotSupportedException).
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
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
VB
My.Computer.FileSystem.MoveFile("C:\TestDir1\test.txt",
"C:\TestDir2\test.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).
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
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
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).
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.
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 source path and target path are the same (IOException).
ShowUI is set to UIOption.AllDialogs and the user cancels the operation, or one or
A file or folder name in the path contains a colon (:) or is in an invalid format
(NotSupportedException).
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
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:
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
VB
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).
A file or folder name in the path contains a colon (:) or is in an invalid format
(NotSupportedException).
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
Use the GetFiles(String) overload for a simple file search in a specified directory,
without searching subdirectories.
An empty collection is returned if no files matching the specified pattern are found.
VB
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).
A file or directory name in the path contains a colon (:) or is in an invalid format
(NotSupportedException).
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.
VB
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.
VB
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.
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
Once the format is defined, you can loop through the file, using the ReadFields method
to process each line in turn.
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.
Encoding Class
The Encoding class represents a character encoding. This table lists the type of
encodings available and describes each.
Name Description
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
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.
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.
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
Read characters from a string How to: Read Characters from a String
To See
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
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.
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
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.
Class Description
Class Description
System.IO.BinaryReader Reads encoded strings and primitive data types from a FileStream.
System.IO.StringReader Reads characters from 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.
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.
Multiline False
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
2. Make sure that the user cannot submit a blank entry by adding the following code
directly after Dim ReadString As String .
VB
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 = ""
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.
Visible False
Size 120,60
Multiline True
Text Display
Enabled False
VB
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.
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
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.
Add the controls in the following table to the form and set the corresponding values for
their properties.
Enabled False
Enabled False
Enabled False
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.
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.
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.
Text Browse
Text Examine
VB
VB
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.
VB
' 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
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.
VB
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.
VB
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.
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.
VB
examineButton.Enabled = anySelected
saveCheckBox.Enabled = anySelected
End Sub
6. Run the application. The Save Results check box and the Examine button are
disabled if an item is not selected in the ListBox .
VB
SetEnabled()
End Sub
' 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
Return sb.ToString
End Function
examineButton.Enabled = anySelected
saveCheckBox.Enabled = anySelected
End Sub
VB
SetEnabled()
End Sub
' 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
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
Return sb.ToString
End Function
examineButton.Enabled = anySelected
saveCheckBox.Enabled = anySelected
End Sub
See also
System.IO
FileSystem
CurrentDirectory
Walkthrough: Manipulating Files by Using .NET Framework Methods