You are on page 1of 181

Table of Contents

Microsoft.VisualBasic.FileIO
DeleteDirectoryOption
DeleteAllContents
ThrowIfDirectoryNonEmpty
FieldType
Delimited
FixedWidth
FileSystem
CombinePath
CopyDirectory
CopyFile
CreateDirectory
CurrentDirectory
DeleteDirectory
DeleteFile
DirectoryExists
Drives
FileExists
FileSystem
FindInFiles
GetDirectories
GetDirectoryInfo
GetDriveInfo
GetFileInfo
GetFiles
GetName
GetParentPath
GetTempFileName
MoveDirectory
MoveFile
OpenTextFieldParser
OpenTextFileReader
OpenTextFileWriter
ReadAllBytes
ReadAllText
RenameDirectory
RenameFile
WriteAllBytes
WriteAllText
MalformedLineException
GetObjectData
LineNumber
MalformedLineException
ToString
RecycleOption
DeletePermanently
SendToRecycleBin
SearchOption
SearchAllSubDirectories
SearchTopLevelOnly
SpecialDirectories
AllUsersApplicationData
CurrentUserApplicationData
Desktop
MyDocuments
MyMusic
MyPictures
ProgramFiles
Programs
SpecialDirectories
Temp
TextFieldParser
Close
CommentTokens
Delimiters
Dispose
EndOfData
ErrorLine
ErrorLineNumber
FieldWidths
Finalize
HasFieldsEnclosedInQuotes
LineNumber
PeekChars
ReadFields
ReadLine
ReadToEnd
SetDelimiters
SetFieldWidths
TextFieldParser
TextFieldType
TrimWhiteSpace
UICancelOption
DoNothing
ThrowException
UIOption
AllDialogs
OnlyErrorDialogs
Microsoft.VisualBasic.FileIO Namespace
The Microsoft.VisualBasic.FileIO namespace contains types that support the My file system object in Visual Basic.

Introduction
For more information about the My system object, see FileSystem.

Classes
FileSystem
Provides properties and methods for working with drives, files,
and directories.

MalformedLineException
The exception that is thrown when the ReadFields() method
cannot parse a row using the specified format.

SpecialDirectories
Provides properties for accessing commonly referenced
directories.

TextFieldParser
Provides methods and properties for parsing structured text
files.

Enums
DeleteDirectoryOption
Specifies what should be done when a directory that is to be
deleted contains files or directories.

FieldType
Indicates whether text fields are delimited or fixed width.

RecycleOption
Specifies whether a file should be deleted permanently or
placed in the Recycle Bin.

SearchOption
Specifies whether to search all or only top-level directories.

UICancelOption
Specifies whether an exception is thrown if the user clicks
Cancel during an operation.

UIOption
Specifies which dialog boxes to show when copying, deleting,
or moving files or directories.
DeleteDirectoryOption Enum
Specifies what should be done when a directory that is to be deleted contains files or directories.

D eclaration
public enum DeleteDirectoryOption

I nheritance H ierarchy
Object
ValueType
Enum

Remarks
This enumeration is used with the DeleteDirectory method.

Fields
DeleteAllContents Delete the contents of the directory along with the directory. Default.

ThrowIfDirectoryNonEmpty Throw an IOException if the directory is not empty. The Data property of the exception lists
the file(s) that could not be deleted.
DeleteDirectoryOption.DeleteAllContents
I n this Article
Delete the contents of the directory along with the directory. Default.
DeleteAllContents

Returns
DeleteDirectoryOption
DeleteDirectoryOption.ThrowIfDirectoryNonEmpty
I n this Article
Throw an IOException if the directory is not empty. The Data property of the exception lists the file(s) that could not be
deleted.
ThrowIfDirectoryNonEmpty

Returns
DeleteDirectoryOption
FieldType Enum
Indicates whether text fields are delimited or fixed width.

D eclaration
public enum FieldType

I nheritance H ierarchy
Object
ValueType
Enum

Remarks
This enumeration is used with the TextFieldParser object.

Fields
Delimited Indicates that the fields are delimited.

FixedWidth Indicates that the fields are fixed width.


FieldType.Delimited
I n this Article
Indicates that the fields are delimited.
Delimited

Returns
FieldType
FieldType.FixedWidth
I n this Article
Indicates that the fields are fixed width.
FixedWidth

Returns
FieldType
FileSystem Class
Provides properties and methods for working with drives, files, and directories.

D eclaration
public class FileSystem

I nheritance H ierarchy
Object

Remarks
The following table lists examples of tasks involving the My.Computer.FileSystem object.

TO S EE

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

Read from a delimited text file How to: Read From Comma-Delimited Text Files

Read from a fixed-width text file How to: Read From Fixed-width Text Files

Read from a text file with multiple formats How to: Read From Text Files with Multiple Formats

Read from a binary file How to: Read From Binary Files

Read from a text file with a StreamReader How to: Read Text from Files with a StreamReader

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

Append to a text file How to: Append to Text Files

Write to a binary file How to: Write to Binary Files

Write to text files in the MyDocuments directory How to: Write Text to Files in the My Documents Directory

Write to a text file with a StreamWriter How to: Write Text to Files with a StreamWriter

Copy files with a specific pattern How to: Copy Files with a Specific Pattern to a Directory

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

Copy a file to a different directory How to: Create a Copy of a File in a Different Directory

Create a file How to: Create a File

Delete a file How to: Delete a File

Find files with a specific pattern How to: Find Files with a Specific Pattern
TO S EE

Move a file How to: Move a File

Rename a file How to: Rename a File

Copy a directory to another directory How to: Copy a Directory to Another Directory

Create a directory How to: Create a Directory

Find subdirectories with a specific pattern How to: Find Subdirectories with a Specific Pattern

Get the collection of files in a directory How to: Get the Collection of Files in a Directory

Read from the MyDocuments directory How to: Retrieve the Contents of the My Documents Directory

Parse a file path How to: Parse File Paths

Constructors
FileSystem()

Initializes a new instance of the FileSystem class.


D eclaration
public FileSystem ();

Properties
CurrentDirectory

Gets or sets the current directory.


D eclaration
public static string CurrentDirectory { get; set; }

P roperty Value
String
The current directory for file I/O operations.

Drives

Returns a read-only collection of all available drive names.


D eclaration
public static System.Collections.ObjectModel.ReadOnlyCollection<System.IO.DriveInfo> Drives {
get; }

P roperty Value
ReadOnlyCollection<DriveInfo>
ReadOnlyCollection<DriveInfo>
A read-only collection of all available drives as DriveInfo objects.

Methods
CombinePath(String, String)

Combines two paths and returns a properly formatted path.


D eclaration
public static string CombinePath (string baseDirectory, string relativePath);

Parameters
baseDirectory String
String . First path to be combined.

relativePath String
String . Second path to be combined.

Returns
String
The combination of the specified paths.

CopyDirectory(String, String)

Copies the contents of a directory to another directory.


D eclaration
public static void CopyDirectory (string sourceDirectoryName, string destinationDirectoryName);

Parameters
sourceDirectoryName String
The directory to be copied.

destinationDirectoryName String
The location to which the directory contents should be copied.

CopyDirectory(String, String, UIOption)

Copies the contents of a directory to another directory.


D eclaration
public static void CopyDirectory (string sourceDirectoryName, string destinationDirectoryName,
Microsoft.VisualBasic.FileIO.UIOption showUI);

Parameters
sourceDirectoryName String
The directory to be copied.

destinationDirectoryName String
The location to which the directory contents should be copied.

showUI UIOption
Whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs .

CopyDirectory(String, String, Boolean)

Copies the contents of a directory to another directory.


D eclaration
public static void CopyDirectory (string sourceDirectoryName, string destinationDirectoryName,
bool overwrite);

Parameters
sourceDirectoryName String
The directory to be copied.

destinationDirectoryName String
The location to which the directory contents should be copied.

overwrite Boolean
True to overwrite existing files; otherwise False . Default is False .

CopyDirectory(String, String, UIOption, UICancelOption)

Copies the contents of a directory to another directory.


D eclaration
public static void CopyDirectory (string sourceDirectoryName, string destinationDirectoryName,
Microsoft.VisualBasic.FileIO.UIOption showUI, Microsoft.VisualBasic.FileIO.UICancelOption
onUserCancel);

Parameters
sourceDirectoryName String
The directory to be copied.

destinationDirectoryName String
The location to which the directory contents should be copied.

showUI UIOption
Whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs .

onUserCancel UICancelOption
Specifies what should be done if the user clicks Cancel during the operation. Default is ThrowException.
CopyFile(String, String)

Copies a file to a new location.


D eclaration
public static void CopyFile (string sourceFileName, string destinationFileName);

Parameters
sourceFileName String
The file to be copied.

destinationFileName String
The location to which the file should be copied.

CopyFile(String, String, UIOption)

Copies a file to a new location.


D eclaration
public static void CopyFile (string sourceFileName, string destinationFileName,
Microsoft.VisualBasic.FileIO.UIOption showUI);

Parameters
sourceFileName String
The file to be copied.

destinationFileName String
The location to which the file should be copied.

showUI UIOption
Whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs .

CopyFile(String, String, Boolean)

Copies a file to a new location.


D eclaration
public static void CopyFile (string sourceFileName, string destinationFileName, bool overwrite);

Parameters
sourceFileName String
The file to be copied.

destinationFileName String
The location to which the file should be copied.

overwrite Boolean
True if existing files should be overwritten; otherwise False . Default is False .
CopyFile(String, String, UIOption, UICancelOption)

Copies a file to a new location.


D eclaration
public static void CopyFile (string sourceFileName, string destinationFileName,
Microsoft.VisualBasic.FileIO.UIOption showUI, Microsoft.VisualBasic.FileIO.UICancelOption
onUserCancel);

Parameters
sourceFileName String
The file to be copied.

destinationFileName String
The location to which the file should be copied.

showUI UIOption
Whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs .

onUserCancel UICancelOption
Specifies what should be done if the user clicks Cancel during the operation. Default is ThrowException.

CreateDirectory(String)

Creates a directory.
D eclaration
public static void CreateDirectory (string directory);

Parameters
directory String
Name and location of the directory.

DeleteDirectory(String, UIOption, RecycleOption, UICancelOption)

Deletes a directory.
D eclaration
public static void DeleteDirectory (string directory, Microsoft.VisualBasic.FileIO.UIOption
showUI, Microsoft.VisualBasic.FileIO.RecycleOption recycle,
Microsoft.VisualBasic.FileIO.UICancelOption onUserCancel);

Parameters
directory String
Directory to be deleted.

showUI UIOption
Specifies whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs .

recycle RecycleOption
Specifies whether or not the deleted file should be sent to the Recycle Bin. Default is RecycleOption.DeletePermanently .

onUserCancel UICancelOption
Specifies whether to throw an exception if the user clicks Cancel.

DeleteDirectory(String, UIOption, RecycleOption)

Deletes a directory.
D eclaration
public static void DeleteDirectory (string directory, Microsoft.VisualBasic.FileIO.UIOption
showUI, Microsoft.VisualBasic.FileIO.RecycleOption recycle);

Parameters
directory String
Directory to be deleted.

showUI UIOption
Specifies whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs .

recycle RecycleOption
Specifies whether or not the deleted file should be sent to the Recycle Bin. Default is RecycleOption.DeletePermanently .

DeleteDirectory(String, DeleteDirectoryOption)

Deletes a directory.
D eclaration
public static void DeleteDirectory (string directory,
Microsoft.VisualBasic.FileIO.DeleteDirectoryOption onDirectoryNotEmpty);

Parameters
directory String
Directory to be deleted.

onDirectoryNotEmpty DeleteDirectoryOption
Specifies what should be done when a directory that is to be deleted contains files or directories. Default is
DeleteDirectoryOption.DeleteAllContents .

DeleteFile(String)

Deletes a file.
D eclaration
public static void DeleteFile (string file);

Parameters
file String
Name and path of the file to be deleted.

DeleteFile(String, UIOption, RecycleOption)

Deletes a file.
D eclaration
public static void DeleteFile (string file, Microsoft.VisualBasic.FileIO.UIOption showUI,
Microsoft.VisualBasic.FileIO.RecycleOption recycle);

Parameters
file String
Name and path of the file to be deleted.

showUI UIOption
Whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs .

recycle RecycleOption
Whether or not the deleted file should be sent to the Recycle Bin. Default is RecycleOption.DeletePermanently .

DeleteFile(String, UIOption, RecycleOption, UICancelOption)

Deletes a file.
D eclaration
public static void DeleteFile (string file, Microsoft.VisualBasic.FileIO.UIOption showUI,
Microsoft.VisualBasic.FileIO.RecycleOption recycle, Microsoft.VisualBasic.FileIO.UICancelOption
onUserCancel);

Parameters
file String
Name and path of the file to be deleted.

showUI UIOption
Whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs .

recycle RecycleOption
Whether or not the deleted file should be sent to the Recycle Bin. Default is RecycleOption.DeletePermanently .

onUserCancel UICancelOption
Specifies whether or not an exception is thrown when the user cancels the operation. Default is UICancelOption.ThrowException .

DirectoryExists(String)

Returns True if the specified directory exists.


D eclaration
public static bool DirectoryExists (string directory);
Parameters
directory String
Path of the directory.

Returns
Boolean
True if the directory exists; otherwise False .

FileExists(String)

Returns True if the specified file exists.


D eclaration
public static bool FileExists (string file);

Parameters
file String
Name and path of the file.

Returns
Boolean
Returns True if the file exists; otherwise this method returns False .

FindInFiles(String, String, Boolean, SearchOption)

Returns a read-only collection of strings representing the names of files containing the specified text.
D eclaration
public static System.Collections.ObjectModel.ReadOnlyCollection<string> FindInFiles (string
directory, string containsText, bool ignoreCase, Microsoft.VisualBasic.FileIO.SearchOption
searchType);

Parameters
directory String
The directory to be searched.

containsText String
The search text.

ignoreCase Boolean
True if the search should be case-sensitive; otherwise False . Default is True .

searchType SearchOption
Whether to include subfolders. Default is SearchOption.SearchTopLevelOnly .

Returns
ReadOnlyCollection<String>
Read-only collection of the names of files containing the specified text..

FindInFiles(String, String, Boolean, SearchOption, String[])

Returns a read-only collection of strings representing the names of files containing the specified text.
D eclaration
public static System.Collections.ObjectModel.ReadOnlyCollection<string> FindInFiles (string
directory, string containsText, bool ignoreCase, Microsoft.VisualBasic.FileIO.SearchOption
searchType, string[] fileWildcards);

Parameters
directory String
The directory to be searched.

containsText String
The search text.

ignoreCase Boolean
True if the search should be case-sensitive; otherwise False . Default is True .

searchType SearchOption
Whether to include subfolders. Default is SearchOption.SearchTopLevelOnly .

fileWildcards String[]
Pattern to be matched.

Returns
ReadOnlyCollection<String>
Read-only collection of the names of files containing the specified text..

GetDirectories(String)

Returns a collection of strings representing the path names of subdirectories within a directory.
D eclaration
public static System.Collections.ObjectModel.ReadOnlyCollection<string> GetDirectories (string
directory);

Parameters
directory String
Name and path of directory.

Returns
ReadOnlyCollection<String>
Read-only collection of the path names of subdirectories within the specified directory..
GetDirectories(String, SearchOption, String[])

Returns a collection of strings representing the path names of subdirectories within a directory.
D eclaration
public static System.Collections.ObjectModel.ReadOnlyCollection<string> GetDirectories (string
directory, Microsoft.VisualBasic.FileIO.SearchOption searchType, string[] wildcards);

Parameters
directory String
Name and path of directory.

searchType SearchOption
Whether to include subfolders. Default is SearchOption.SearchTopLevelOnly .

wildcards String[]
Pattern to match names.

Returns
ReadOnlyCollection<String>
Read-only collection of the path names of subdirectories within the specified directory.

GetDirectoryInfo(String)

Returns a DirectoryInfo object for the specified path.


D eclaration
public static System.IO.DirectoryInfo GetDirectoryInfo (string directory);

Parameters
directory String
String . Path of directory.

Returns
DirectoryInfo
DirectoryInfo object for the specified path.

GetDriveInfo(String)

Returns a DriveInfo object for the specified drive.


D eclaration
public static System.IO.DriveInfo GetDriveInfo (string drive);

Parameters
drive String
Drive to be examined.
Returns
DriveInfo
DriveInfo object for the specified drive.

GetFileInfo(String)

Returns a FileInfo object for the specified file.


D eclaration
public static System.IO.FileInfo GetFileInfo (string file);

Parameters
file String
Name and path of the file.

Returns
FileInfo
FileInfo object for the specified file

GetFiles(String)

Returns a read-only collection of strings representing the names of files within a directory.
D eclaration
public static System.Collections.ObjectModel.ReadOnlyCollection<string> GetFiles (string
directory);

Parameters
directory String
Directory to be searched.

Returns
ReadOnlyCollection<String>
Read-only collection of file names from the specified directory.

GetFiles(String, SearchOption, String[])

Returns a read-only collection of strings representing the names of files within a directory.
D eclaration
public static System.Collections.ObjectModel.ReadOnlyCollection<string> GetFiles (string
directory, Microsoft.VisualBasic.FileIO.SearchOption searchType, string[] wildcards);

Parameters
directory String
Directory to be searched.

searchType SearchOption
Whether to include subfolders. Default is SearchOption.SearchTopLevelOnly .

wildcards String[]
Pattern to be matched.

Returns
ReadOnlyCollection<String>
Read-only collection of file names from the specified directory.

GetName(String)

Parses the file name out of the path provided.


D eclaration
public static string GetName (string path);

Parameters
path String
Required. Path to be parsed. String .

Returns
String
The file name from the specified path.

GetParentPath(String)

Returns the parent path of the provided path.


D eclaration
public static string GetParentPath (string path);

Parameters
path String
Path to be examined.

Returns
String
The parent path of the provided path.

GetTempFileName()

Creates a uniquely named zero-byte temporary file on disk and returns the full path of that file.
D eclaration
D eclaration
public static string GetTempFileName ();

Returns
String
String containing the full path of the temporary file.

MoveDirectory(String, String)

Moves a directory from one location to another.


D eclaration
public static void MoveDirectory (string sourceDirectoryName, string destinationDirectoryName);

Parameters
sourceDirectoryName String
Path of the directory to be moved.

destinationDirectoryName String
Path of the directory to which the source directory is being moved.

MoveDirectory(String, String, UIOption)

Moves a directory from one location to another.


D eclaration
public static void MoveDirectory (string sourceDirectoryName, string destinationDirectoryName,
Microsoft.VisualBasic.FileIO.UIOption showUI);

Parameters
sourceDirectoryName String
Path of the directory to be moved.

destinationDirectoryName String
Path of the directory to which the source directory is being moved.

showUI UIOption
Specifies whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs .

MoveDirectory(String, String, Boolean)

Moves a directory from one location to another.


D eclaration
public static void MoveDirectory (string sourceDirectoryName, string destinationDirectoryName,
bool overwrite);

Parameters
sourceDirectoryName String
Path of the directory to be moved.

destinationDirectoryName String
Path of the directory to which the source directory is being moved.

overwrite Boolean
True if existing directories should be overwritten; otherwise False . Default is False .

MoveDirectory(String, String, UIOption, UICancelOption)

Moves a directory from one location to another.


D eclaration
public static void MoveDirectory (string sourceDirectoryName, string destinationDirectoryName,
Microsoft.VisualBasic.FileIO.UIOption showUI, Microsoft.VisualBasic.FileIO.UICancelOption
onUserCancel);

Parameters
sourceDirectoryName String
Path of the directory to be moved.

destinationDirectoryName String
Path of the directory to which the source directory is being moved.

showUI UIOption
Specifies whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs .

onUserCancel UICancelOption
Specifies whether or not an exception is thrown when the user cancels the operation. Default is UICancelOption.ThrowException .

MoveFile(String, String)

Moves a file to a new location.


D eclaration
public static void MoveFile (string sourceFileName, string destinationFileName);

Parameters
sourceFileName String
Path of the file to be moved.

destinationFileName String
Path of the directory into which the file should be moved.

MoveFile(String, String, UIOption)

Moves a file to a new location.


D eclaration
public static void MoveFile (string sourceFileName, string destinationFileName,
Microsoft.VisualBasic.FileIO.UIOption showUI);

Parameters
sourceFileName String
Path of the file to be moved.

destinationFileName String
Path of the directory into which the file should be moved.

showUI UIOption
Specifies whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs .

MoveFile(String, String, Boolean)

Moves a file to a new location.


D eclaration
public static void MoveFile (string sourceFileName, string destinationFileName, bool overwrite);

Parameters
sourceFileName String
Path of the file to be moved.

destinationFileName String
Path of the directory into which the file should be moved.

overwrite Boolean
True to overwrite existing files; otherwise False . Default is False .

MoveFile(String, String, UIOption, UICancelOption)

Moves a file to a new location.


D eclaration
public static void MoveFile (string sourceFileName, string destinationFileName,
Microsoft.VisualBasic.FileIO.UIOption showUI, Microsoft.VisualBasic.FileIO.UICancelOption
onUserCancel);

Parameters
sourceFileName String
Path of the file to be moved.

destinationFileName String
Path of the directory into which the file should be moved.

showUI UIOption
Specifies whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs .

onUserCancel UICancelOption
Specifies whether or not an exception is thrown when the user cancels the operation. Default is UICancelOption.ThrowException .

OpenTextFieldParser(String, String[])

The OpenTextFieldParser method allows you to create a TextFieldParser object, which provides a way to easily
and efficiently parse structured text files, such as logs. The TextFieldParser object can be used to read both
delimited and fixed-width files.
D eclaration
public static Microsoft.VisualBasic.FileIO.TextFieldParser OpenTextFieldParser (string file,
string[] delimiters);

Parameters
file String
The file to be opened with the TextFieldParser .

delimiters String[]
Delimiters for the fields.

Returns
TextFieldParser
TextFieldParser to read the specified file.

OpenTextFieldParser(String)

The OpenTextFieldParser method allows you to create a TextFieldParser object, which provides a way to easily
and efficiently parse structured text files, such as logs. The TextFieldParser object can be used to read both
delimited and fixed-width files.
D eclaration
public static Microsoft.VisualBasic.FileIO.TextFieldParser OpenTextFieldParser (string file);

Parameters
file String
The file to be opened with the TextFieldParser .

Returns
TextFieldParser
TextFieldParser to read the specified file.

OpenTextFieldParser(String, Int32[])

The OpenTextFieldParser method allows you to create a TextFieldParser object, which provides a way to easily
and efficiently parse structured text files, such as logs. The TextFieldParser object can be used to read both
delimited and fixed-width files.
D eclaration
public static Microsoft.VisualBasic.FileIO.TextFieldParser OpenTextFieldParser (string file,
int[] fieldWidths);

Parameters
file String
The file to be opened with the TextFieldParser .

fieldWidths Int32[]
Widths of the fields.

Returns
TextFieldParser
TextFieldParser to read the specified file.

OpenTextFileReader(String)

Opens a StreamReader object to read from a file.


D eclaration
public static System.IO.StreamReader OpenTextFileReader (string file);

Parameters
file String
File to be read.

Returns
StreamReader
StreamReader object to read from the file

OpenTextFileReader(String, Encoding)

Opens a StreamReader object to read from a file.


D eclaration
public static System.IO.StreamReader OpenTextFileReader (string file, System.Text.Encoding
encoding);

Parameters
file String
File to be read.

encoding Encoding
The encoding to use for the file contents. Default is ASCII.
Returns
StreamReader
StreamReader object to read from the file

OpenTextFileWriter(String, Boolean)

Opens a StreamWriter object to write to the specified file.


D eclaration
public static System.IO.StreamWriter OpenTextFileWriter (string file, bool append);

Parameters
file String
File to be written to.

append Boolean
True to append to the contents of the file; False to overwrite the contents of the file. Default is False .

Returns
StreamWriter
StreamWriter object to write to the specified file.

OpenTextFileWriter(String, Boolean, Encoding)

Opens a StreamWriter to write to the specified file.


D eclaration
public static System.IO.StreamWriter OpenTextFileWriter (string file, bool append,
System.Text.Encoding encoding);

Parameters
file String
File to be written to.

append Boolean
True to append to the contents in the file; False to overwrite the contents of the file. Default is False .

encoding Encoding
Encoding to be used in writing to the file. Default is ASCII.

Returns
StreamWriter
StreamWriter object to write to the specified file.

ReadAllBytes(String)
Returns the contents of a file as a byte array.
D eclaration
public static byte[] ReadAllBytes (string file);

Parameters
file String
File to be read.

Returns
Byte[]
Byte array containing the contents of the file.

ReadAllText(String)

Returns the contents of a text file as a String .


D eclaration
public static string ReadAllText (string file);

Parameters
file String
Name and path of the file to read.

Returns
String
String containing the contents of the file.

ReadAllText(String, Encoding)

Returns the contents of a text file as a String .


D eclaration
public static string ReadAllText (string file, System.Text.Encoding encoding);

Parameters
file String
Name and path of the file to read.

encoding Encoding
Character encoding to use in reading the file. Default is UTF-8.

Returns
String
String containing the contents of the file.
RenameDirectory(String, String)

Renames a directory.
D eclaration
public static void RenameDirectory (string directory, string newName);

Parameters
directory String
Path and name of directory to be renamed.

newName String
New name for directory.

RenameFile(String, String)

Renames a file.
D eclaration
public static void RenameFile (string file, string newName);

Parameters
file String
File to be renamed.

newName String
New name of file.

WriteAllBytes(String, Byte[], Boolean)

Writes data to a binary file.


D eclaration
public static void WriteAllBytes (string file, byte[] data, bool append);

Parameters
file String
Path and name of the file to be written to.

data Byte[]
Data to be written to the file.

append Boolean
True to append to the file contents; False to overwrite the file contents. Default is False .

WriteAllText(String, String, Boolean)

Writes text to a file.


D eclaration
public static void WriteAllText (string file, string text, bool append);

Parameters
file String
File to be written to.

text String
Text to be written to file.

append Boolean
True to append to the contents of the file; False to overwrite the contents of the file.

WriteAllText(String, String, Boolean, Encoding)

Writes text to a file.


D eclaration
public static void WriteAllText (string file, string text, bool append, System.Text.Encoding
encoding);

Parameters
file String
File to be written to.

text String
Text to be written to file.

append Boolean
True to append to the contents of the file; False to overwrite the contents of the file.

encoding Encoding
What encoding to use when writing to file.
FileSystem.CombinePath
I n this Article
Combines two paths and returns a properly formatted path.
public static string CombinePath (string baseDirectory, string relativePath);

Parameters
baseDirectory String
String . First path to be combined.

relativePath String
String . Second path to be combined.

Returns
String
The combination of the specified paths.
Exceptions
ArgumentException
baseDirectory or relativePath are malformed paths.

Examples
This example combines a directory path and file name to create a properly formatted path.
This example combines two paths to create a properly formatted path.
This example returns C:\Dir1\Dir2\Dir4\Dir5\File.txt .

Remarks
This method trims excess slash-mark characters to create a properly formatted path.
The following table lists an example of a task involving the My.Computer.FileSystem.CombinePath method.

TO S EE

Combine a directory path and file name How to: Parse File Paths in Visual Basic
FileSystem.CopyDirectory
I n this Article

Overloads
Copy​Directory(​String, ​String)
Copies the contents of a directory to another directory.

Copy​Directory(​String, ​String, ​UI​Option)


Copies the contents of a directory to another directory.

Copy​Directory(​String, ​String, ​Boolean)


Copies the contents of a directory to another directory.

Copy​Directory(​String, ​String, ​UI​Option, ​UI​Cancel​Option)


Copies the contents of a directory to another directory.

CopyDirectory(String, String)
Copies the contents of a directory to another directory.
public static void CopyDirectory (string sourceDirectoryName, string destinationDirectoryName);

Parameters
sourceDirectoryName String
The directory to be copied.
destinationDirectoryName String
The location to which the directory contents should be copied.
Exceptions
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 \\.\).
ArgumentNullException
destinationDirectoryName or sourceDirectoryName is Nothing or an empty string.
DirectoryNotFoundException
The source directory does not exist.
IOException
The source path and target path are the same.
InvalidOperationException
The operation is cyclic.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A folder name in the path contains a colon (:) or is in an invalid format.
SecurityException
The user lacks necessary permissions to view the path.
UnauthorizedAccessException
A destination file exists but cannot be accessed.
Examples
The following example copies the contents of directory TestDirectory1 into TestDirectory2 , overwriting existing
files.
Replace C: estDirectory1 and C: estDirectory2 with the path and name of the directory you wish to copy
and the location to which you wish to copy it.
Remarks
This method copies the contents of the source directory to the target directory. If the target directory does not exist, it is
created. If a directory with the same name exists in the target location, the contents of the two directories are 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 a specific file. When such
exceptions are thrown, they are consolidated into a single exception whose Data property holds entries in the form of
an IDictionary in which the file or directory path is the key and the specific exception message is contained in the
corresponding value. Use For…Each to enumerate through the entries.

The following table lists an example of a task involving the My.Computer.FileSystem.CopyDirectory method.

TO S EE

Copy a directory How to: Copy a Directory to Another Directory in Visual Basic

CopyDirectory(String, String, UIOption)


Copies the contents of a directory to another directory.

public static void CopyDirectory (string sourceDirectoryName, string destinationDirectoryName,


Microsoft.VisualBasic.FileIO.UIOption showUI);

Parameters
sourceDirectoryName String
The directory to be copied.
destinationDirectoryName String
The location to which the directory contents should be copied.
showUI UIOption
Whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs .

Exceptions
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 \\.\).
ArgumentNullException
destinationDirectoryName or sourceDirectoryName is Nothing or an empty string.
DirectoryNotFoundException
The source directory does not exist.
IOException
The source path and target path are the same.
InvalidOperationException
The operation is cyclic.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A folder name in the path contains a colon (:) or is in an invalid format.
SecurityException
The user lacks necessary permissions to view the path.
UnauthorizedAccessException
A destination file exists but cannot be accessed.
OperationCanceledException
ShowUI is set to UIOption.AllDialogs and the user cancels the operation, or one or more files in the directory cannot
be copied.
Examples
The following example copies the contents of directory TestDirectory1 into TestDirectory2 , overwriting existing
files.
Replace C: estDirectory1 and C: estDirectory2 with the path and name of the directory you wish to copy
and the location to which you wish to copy it.
Remarks
This method copies the contents of the source directory to the target directory. If the target directory does not exist, it is
created. If a directory with the same name exists in the target location, the contents of the two directories are 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 a specific file. When such
exceptions are thrown, they are consolidated into a single exception whose Data property holds entries in the form of
an IDictionary in which the file or directory path is the key and the specific exception message is contained in the
corresponding value. Use For…Each to enumerate through the entries.

The following table lists an example of a task involving the My.Computer.FileSystem.CopyDirectory method.

TO S EE

Copy a directory How to: Copy a Directory to Another Directory in Visual Basic

CopyDirectory(String, String, Boolean)


Copies the contents of a directory to another directory.

public static void CopyDirectory (string sourceDirectoryName, string destinationDirectoryName, bool


overwrite);

Parameters
sourceDirectoryName String
The directory to be copied.
destinationDirectoryName String
The location to which the directory contents should be copied.
overwrite Boolean
True to overwrite existing files; otherwise False . Default is False .

Exceptions
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 \\.\).
ArgumentNullException
destinationDirectoryName or sourceDirectoryName is Nothing or an empty string.

DirectoryNotFoundException
The source directory does not exist.
IOException
The source path and target path are the same.
InvalidOperationException
The operation is cyclic.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A folder name in the path contains a colon (:) or is in an invalid format.
SecurityException
The user lacks necessary permissions to view the path.
UnauthorizedAccessException
A destination file exists but cannot be accessed.
Examples
The following example copies the contents of directory TestDirectory1 into TestDirectory2 , overwriting existing
files.
Replace C: estDirectory1 and C: estDirectory2 with the path and name of the directory you wish to copy
and the location to which you wish to copy it.
Remarks
This method copies the contents of the source directory to the target directory. If the target directory does not exist, it is
created. If a directory with the same name exists in the target location, the contents of the two directories are 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 a 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 the form of an IDictionary in which the file or directory path is the key
and the specific exception message is contained in the corresponding value. Use For…Each to enumerate through the
entries.
The following table lists an example of a task involving the My.Computer.FileSystem.CopyDirectory method.

TO S EE

Copy a directory How to: Copy a Directory to Another Directory in Visual Basic

CopyDirectory(String, String, UIOption, UICancelOption)


Copies the contents of a directory to another directory.

public static void CopyDirectory (string sourceDirectoryName, string destinationDirectoryName,


Microsoft.VisualBasic.FileIO.UIOption showUI, Microsoft.VisualBasic.FileIO.UICancelOption
onUserCancel);

Parameters
sourceDirectoryName String
The directory to be copied.
destinationDirectoryName String
The location to which the directory contents should be copied.
showUI UIOption
Whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs .

onUserCancel UICancelOption
Specifies what should be done if the user clicks Cancel during the operation. Default is ThrowException.
Exceptions
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 \\.\).
ArgumentNullException
destinationDirectoryName or sourceDirectoryName is Nothing or an empty string.

DirectoryNotFoundException
The source directory does not exist.
IOException
The source path and target path are the same.
InvalidOperationException
The operation is cyclic.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A folder name in the path contains a colon (:) or is in an invalid format.
SecurityException
The user lacks necessary permissions to view the path.
UnauthorizedAccessException
A destination file exists but cannot be accessed.
OperationCanceledException
ShowUI is set to UIOption.AllDialogs and the user cancels the operation, or one or more files in the directory cannot
be copied.
Examples
The following example copies the contents of directory TestDirectory1 into TestDirectory2 , overwriting existing
files.
Replace C: estDirectory1 and C: estDirectory2 with the path and name of the directory you wish to copy
and the location to which you wish to copy it.
Remarks
This method copies the contents of the source directory to the target directory. If the target directory does not exist, it is
created. If a directory with the same name exists in the target location, the contents of the two directories are 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 a specific file. When such
exceptions are thrown, they are consolidated into a single exception whose Data property holds entries in the form of
an IDictionary in which the file or directory path is the key and the specific exception message is contained in the
corresponding value. Use For…Each to enumerate through the entries.
The following table lists an example of a task involving the My.Computer.FileSystem.CopyDirectory method.

TO S EE

Copy a directory How to: Copy a Directory to Another Directory in Visual Basic
FileSystem.CopyFile
I n this Article

Overloads
Copy​File(​String, ​String)
Copies a file to a new location.

Copy​File(​String, ​String, ​UI​Option)


Copies a file to a new location.

Copy​File(​String, ​String, ​Boolean)


Copies a file to a new location.

Copy​File(​String, ​String, ​UI​Option, ​UI​Cancel​Option)


Copies a file to a new location.

CopyFile(String, String)
Copies a file to a new location.
public static void CopyFile (string sourceFileName, string destinationFileName);

Parameters
sourceFileName String
The file to be copied.
destinationFileName String
The location to which the file should be copied.
Exceptions
ArgumentException
destinationFileName contains path information.

ArgumentNullException
destinationFileName or sourceFileName is Nothing or an empty string.
FileNotFoundException
The source file is not valid or does not exist.
IOException
A file in the target directory with the same name is in use.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
PathTooLongException
The path exceeds the system-defined maximum length.
UnauthorizedAccessException
The user does not have required permission.
SecurityException
The user lacks necessary permissions to view the path.
Examples
This example copies the file Test.txt to the directory TestFiles2 without overwriting existing files.
Replace the file paths with the paths you want to use in your code.
This example copies the file Test.txt to the directory TestFiles2 and renames it NewFile.txt .
Replace the file paths with the paths you want to use in your code.
Remarks
CopyFile does not preserve ACEs (Access Control Entries). The newly created file inherits default ACEs from the
directory in which it is created.
The following table lists examples of tasks involving the My.Computer.FileSystem.CopyFile method.

TO S EE

Copy a file to the same directory. How to: Create a Copy of a File in the Same Directory in Visual
Basic

Copy a file to a different directory. How to: Create a Copy of a File in a Different Directory in
Visual Basic

CopyFile(String, String, UIOption)


Copies a file to a new location.
public static void CopyFile (string sourceFileName, string destinationFileName,
Microsoft.VisualBasic.FileIO.UIOption showUI);

Parameters
sourceFileName String
The file to be copied.
destinationFileName String
The location to which the file should be copied.
showUI UIOption
Whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs .
Exceptions
ArgumentException
destinationFileName contains path information.
ArgumentNullException
destinationFileName or sourceFileName is Nothing or an empty string.
FileNotFoundException
The source file is not valid or does not exist.
IOException
The destination file exists and overwrite is set to False .

NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
PathTooLongException
The path exceeds the system-defined maximum length.
UnauthorizedAccessException
The user does not have required permission.
SecurityException
The user lacks necessary permissions to view the path.
Examples
This example copies the file Test.txt to the directory TestFiles2 without overwriting existing files.

Replace the file paths with the paths you want to use in your code.
This example copies the file Test.txt to the directory TestFiles2 and renames it NewFile.txt .

Replace the file paths with the paths you want to use in your code.
Remarks
CopyFile does not preserve ACEs (Access Control Entries). The newly created file inherits default ACEs from the
directory in which it is created.
The following table lists examples of tasks involving the My.Computer.FileSystem.CopyFile method.

TO S EE

Copy a file to the same directory. How to: Create a Copy of a File in the Same Directory in Visual
Basic

Copy a file to a different directory. How to: Create a Copy of a File in a Different Directory in
Visual Basic

CopyFile(String, String, Boolean)


Copies a file to a new location.

public static void CopyFile (string sourceFileName, string destinationFileName, bool overwrite);

Parameters
sourceFileName String
The file to be copied.
destinationFileName String
The location to which the file should be copied.
overwrite Boolean
True if existing files should be overwritten; otherwise False . Default is False .

Exceptions
ArgumentException
destinationFileName contains path information.

ArgumentNullException
destinationFileName or sourceFileName is Nothing or an empty string.

FileNotFoundException
The source file is not valid or does not exist.
IOException
The destination file exists and overwrite is set to False .

NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
PathTooLongException
The path exceeds the system-defined maximum length.
UnauthorizedAccessException
The user does not have required permission.
SecurityException
The user lacks necessary permissions to view the path.
Examples
This example copies the file Test.txt to the directory TestFiles2 without overwriting existing files.

Replace the file paths with the paths you want to use in your code.
This example copies the file Test.txt to the directory TestFiles2 and renames it NewFile.txt .

Replace the file paths with the paths you want to use in your code.
Remarks
CopyFile does not preserve ACEs (Access Control Entries). The newly created file inherits default ACEs from the
directory in which it is created.
The following table lists examples of tasks involving the My.Computer.FileSystem.CopyFile method.
TO S EE

Copy a file to the same directory. How to: Create a Copy of a File in the Same Directory in Visual
Basic

Copy a file to a different directory. How to: Create a Copy of a File in a Different Directory in
Visual Basic

CopyFile(String, String, UIOption, UICancelOption)


Copies a file to a new location.

public static void CopyFile (string sourceFileName, string destinationFileName,


Microsoft.VisualBasic.FileIO.UIOption showUI, Microsoft.VisualBasic.FileIO.UICancelOption
onUserCancel);

Parameters
sourceFileName String
The file to be copied.
destinationFileName String
The location to which the file should be copied.
showUI UIOption
Whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs .
onUserCancel UICancelOption
Specifies what should be done if the user clicks Cancel during the operation. Default is ThrowException.
Exceptions
ArgumentException
destinationFileName contains path information.

ArgumentNullException
destinationFileName or sourceFileName is Nothing or an empty string.

FileNotFoundException
The source file is not valid or does not exist.
IOException
The destination file exists and overwrite is set to False .
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
PathTooLongException
The path exceeds the system-defined maximum length.
UnauthorizedAccessException
The user does not have required permission.
SecurityException
The user lacks necessary permissions to view the path.
OperationCanceledException
UICancelOption is set to ThrowException , and the user has canceled the operation or an unspecified I/O error occurs.
Examples
This example copies the file Test.txt to the directory TestFiles2 without overwriting existing files.
Replace the file paths with the paths you want to use in your code.
This example copies the file Test.txt to the directory TestFiles2 and renames it NewFile.txt .

Replace the file paths with the paths you want to use in your code.
Remarks
CopyFile does not preserve ACEs (Access Control Entries). The newly created file inherits default ACEs from the
directory in which it is created.
The following table lists examples of tasks involving the My.Computer.FileSystem.CopyFile method.

TO S EE

Copy a file to the same directory. How to: Create a Copy of a File in the Same Directory in Visual
Basic

Copy a file to a different directory. How to: Create a Copy of a File in a Different Directory in
Visual Basic
FileSystem.CreateDirectory
I n this Article
Creates a directory.
public static void CreateDirectory (string directory);

Parameters
directory String
Name and location of the directory.
Exceptions
ArgumentException
The directory name is malformed. For example, it contains illegal characters or is only white space.
ArgumentNullException
directory is Nothing or an empty string.

PathTooLongException
The directory name is too long.
NotSupportedException
The directory name is only a colon (:).
IOException
The parent directory of the directory to be created is read-only
UnauthorizedAccessException
The user does not have permission to create the directory.

Examples
This example creates the directory, NewDirectory , in C:\Documents and Settings\All Users\Documents .

Remarks
If the directory already exists, no exception is thrown.
The following table lists an example of a task involving the My.Computer.FileSystem.CreateDirectory method.

TO S EE

Create a directory How to: Create a Directory in Visual Basic


FileSystem.CurrentDirectory
I n this Article
Gets or sets the current directory.
public static string CurrentDirectory { get; set; }

Returns
String
The current directory for file I/O operations.
Exceptions
DirectoryNotFoundException
The path is not valid.
UnauthorizedAccessException
The user lacks necessary permissions.

Examples
This example returns the current directory and displays it in a message box.
This example sets the current directory to C: estDirectory .

Remarks
CurrentDirectory is a system-wide environment variable.
FileSystem.DeleteDirectory
I n this Article

Overloads
Delete​Directory(​String, ​UI​Option, ​Recycle​Option, ​UI​Cancel​
Option) Deletes a directory.

Delete​Directory(​String, ​UI​Option, ​Recycle​Option)


Deletes a directory.

Delete​Directory(​String, ​Delete​Directory​Option)
Deletes a directory.

DeleteDirectory(String, UIOption, RecycleOption, UICancelOption)


Deletes a directory.
public static void DeleteDirectory (string directory, Microsoft.VisualBasic.FileIO.UIOption showUI,
Microsoft.VisualBasic.FileIO.RecycleOption recycle, Microsoft.VisualBasic.FileIO.UICancelOption
onUserCancel);

Parameters
directory String
Directory to be deleted.
showUI UIOption
Specifies whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs .
recycle RecycleOption
Specifies whether or not the deleted file should be sent to the Recycle Bin. Default is
RecycleOption.DeletePermanently .

onUserCancel UICancelOption
Specifies whether to throw an exception if the user clicks Cancel.
Exceptions
ArgumentException
The path is a zero-length string, is malformed, contains only white space, or contains invalid characters (including
wildcard characters). The path is a device path (starts with \\.\).
ArgumentNullException
directory is Nothing or an empty string.
DirectoryNotFoundException
The directory does not exist or is a file.
IOException
A file in the directory or subdirectory is in use.
NotSupportedException
The directory name contains a colon (:).
PathTooLongException
The path exceeds the system-defined maximum length.
SecurityException
The user does not have required permissions.
OperationCanceledException
The user cancels the operation or the directory cannot be deleted.
Examples
The example deletes the directory OldDirectory only if it is empty.
This example deletes the directory OldDirectory and all of its contents.

This example deletes the directory OldDirectory and all of its contents, asking the user to confirm the deletion, but
does not send the contents to the Recycle Bin.
This example deletes the directory OldDirectory and all of its contents, sending them to the Recycle Bin, but does not
show the progress of the operation.
Remarks
The showUI , recycle , and onUserCancel parameters are not supported in applications that are not user interactive,
such as Windows Services.

DeleteDirectory(String, UIOption, RecycleOption)


Deletes a directory.

public static void DeleteDirectory (string directory, Microsoft.VisualBasic.FileIO.UIOption showUI,


Microsoft.VisualBasic.FileIO.RecycleOption recycle);

Parameters
directory String
Directory to be deleted.
showUI UIOption
Specifies whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs .

recycle RecycleOption
Specifies whether or not the deleted file should be sent to the Recycle Bin. Default is
RecycleOption.DeletePermanently .

Exceptions
ArgumentException
The path is a zero-length string, is malformed, contains only white space, or contains invalid characters (including
wildcard characters). The path is a device path (starts with \\.\).
ArgumentNullException
directory is Nothing or an empty string.
DirectoryNotFoundException
The directory does not exist or is a file.
IOException
A file in the directory or subdirectory is in use.
NotSupportedException
The directory name contains a colon (:).
PathTooLongException
The path exceeds the system-defined maximum length.
SecurityException
The user does not have required permissions.
OperationCanceledException
The user cancels the operation or the directory cannot be deleted.
Examples
The example deletes the directory OldDirectory only if it is empty.
This example deletes the directory OldDirectory and all of its contents.

This example deletes the directory OldDirectory and all of its contents, asking the user to confirm the deletion, but
does not send the contents to the Recycle Bin.
This example deletes the directory OldDirectory and all of its contents, sending them to the Recycle Bin, but does not
show the progress of the operation.
Remarks
The showUI and recycle parameters are not supported in applications that are not user interactive, such as Windows
Services.

DeleteDirectory(String, DeleteDirectoryOption)
Deletes a directory.

public static void DeleteDirectory (string directory,


Microsoft.VisualBasic.FileIO.DeleteDirectoryOption onDirectoryNotEmpty);

Parameters
directory String
Directory to be deleted.
onDirectoryNotEmpty DeleteDirectoryOption
Specifies what should be done when a directory that is to be deleted contains files or directories. Default is
DeleteDirectoryOption.DeleteAllContents .

Exceptions
ArgumentException
The path is a zero-length string, is malformed, contains only white space, or contains invalid characters (including
wildcard characters). The path is a device path (starts with \\.\).
ArgumentNullException
directory is Nothing or an empty string.

DirectoryNotFoundException
The directory does not exist or is a file.
IOException
A file in the directory or subdirectory is in use.
NotSupportedException
The directory name contains a colon (:).
PathTooLongException
The path exceeds the system-defined maximum length.
SecurityException
The user does not have required permissions.
OperationCanceledException
The user cancels the operation or the directory cannot be deleted.
Examples
The example deletes the directory OldDirectory only if it is empty.

This example deletes the directory OldDirectory and all of its contents.

This example deletes the directory OldDirectory and all of its contents, asking the user to confirm the deletion, but
does not send the contents to the Recycle Bin.
This example deletes the directory OldDirectory and all of its contents, sending them to the Recycle Bin, but does not
show the progress of the operation.
FileSystem.DeleteFile
I n this Article

Overloads
Delete​File(​String)
Deletes a file.

Delete​File(​String, ​UI​Option, ​Recycle​Option)


Deletes a file.

Delete​File(​String, ​UI​Option, ​Recycle​Option, ​UI​Cancel​Option)


Deletes a file.

DeleteFile(String)
Deletes a file.
public static void DeleteFile (string file);

Parameters
file String
Name and path of the file to be deleted.
Exceptions
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; it has a trailing slash where a file must be specified; or it is a device path (starts with \\.\).
ArgumentNullException
file is Nothing or an empty string.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
IOException
The file is in use.
SecurityException
The user lacks necessary permissions to view the path.
FileNotFoundException
The file does not exist.
UnauthorizedAccessException
The user does not have permission to delete the file or the file is read-only.
Examples
This example deletes the file Test.txt .
This example deletes the file Test.txt and allows the user to confirm that the file should be deleted.
This example deletes the file Test.txt and sends it to the Recycle Bin.
Remarks
The following table lists an example of a task involving the My.Computer.FileSystem.DeleteFile method.

TO S EE

To delete a file How to: Delete a File in Visual Basic

DeleteFile(String, UIOption, RecycleOption)


Deletes a file.
public static void DeleteFile (string file, Microsoft.VisualBasic.FileIO.UIOption showUI,
Microsoft.VisualBasic.FileIO.RecycleOption recycle);

Parameters
file String
Name and path of the file to be deleted.
showUI UIOption
Whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs .

recycle RecycleOption
Whether or not the deleted file should be sent to the Recycle Bin. Default is RecycleOption.DeletePermanently .

Exceptions
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; it has a trailing slash where a file must be specified; or it is a device path (starts with \\.\).
ArgumentNullException
file is Nothing or an empty string.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
IOException
The file is in use.
SecurityException
The user lacks necessary permissions to view the path.
FileNotFoundException
The file does not exist.
UnauthorizedAccessException
The user does not have permission to delete the file or the file is read-only.
Examples
This example deletes the file Test.txt .

This example deletes the file Test.txt and allows the user to confirm that the file should be deleted.
This example deletes the file Test.txt and sends it to the Recycle Bin.
Remarks
The showUI and recycle parameters are not supported in applications that are not user interactive, such as Windows
Services.
The following table lists an example of a task involving the My.Computer.FileSystem.DeleteFile method.

TO S EE

To delete a file How to: Delete a File in Visual Basic

DeleteFile(String, UIOption, RecycleOption, UICancelOption)


Deletes a file.

public static void DeleteFile (string file, Microsoft.VisualBasic.FileIO.UIOption showUI,


Microsoft.VisualBasic.FileIO.RecycleOption recycle, Microsoft.VisualBasic.FileIO.UICancelOption
onUserCancel);

Parameters
file String
Name and path of the file to be deleted.
showUI UIOption
Whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs .

recycle RecycleOption
Whether or not the deleted file should be sent to the Recycle Bin. Default is RecycleOption.DeletePermanently .

onUserCancel UICancelOption
Specifies whether or not an exception is thrown when the user cancels the operation. Default is
UICancelOption.ThrowException .
Exceptions
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; it has a trailing slash where a file must be specified; or it is a device path (starts with \\.\).
ArgumentNullException
file is Nothing or an empty string.

PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
IOException
The file is in use.
SecurityException
The user lacks necessary permissions to view the path.
FileNotFoundException
The file does not exist.
UnauthorizedAccessException
The user does not have permission to delete the file or the file is read-only.
OperationCanceledException
The user cancelled the operation and onUserCancel is set to ThrowException.
Examples
This example deletes the file Test.txt .
This example deletes the file Test.txt and allows the user to confirm that the file should be deleted.

This example deletes the file Test.txt and sends it to the Recycle Bin.
Remarks
The showUI , recycle , and onUserCancel parameters are not supported in applications that are not user interactive,
such as Windows Services.
The following table lists an example of a task involving the My.Computer.FileSystem.DeleteFile method.

TO S EE

To delete a file How to: Delete a File in Visual Basic


FileSystem.DirectoryExists
I n this Article
Returns True if the specified directory exists.

public static bool DirectoryExists (string directory);

Parameters
directory String
Path of the directory.
Returns
Boolean
True if the directory exists; otherwise False .

Examples
This example determines whether the directory C:\backup\logs exists and checks its properties.
FileSystem.Drives
I n this Article

This API is not CLS-compliant.


CLS- None
compliant
alternative

Returns a read-only collection of all available drive names.


public static System.Collections.ObjectModel.ReadOnlyCollection<System.IO.DriveInfo> Drives { get; }

Returns
ReadOnlyCollection<DriveInfo>
A read-only collection of all available drives as DriveInfo objects.

Examples
This example displays the available drive names in a message box.

Remarks
This property returns all logical drives.
FileSystem.FileExists
I n this Article
Returns True if the specified file exists.

public static bool FileExists (string file);

Parameters
file String
Name and path of the file.
Returns
Boolean
Returns True if the file exists; otherwise this method returns False .
Exceptions
ArgumentException
The name of the file ends with a backslash (\).

Examples
This example checks to see whether or not the file Check.txt exists and supplies the information in a message box.

Remarks
If the application does not have sufficient permissions to read the specified file, the FileExists method returns False ,
regardless of the existence of the path; the method does not throw an exception.
FileSystem
I n this Article
Initializes a new instance of the FileSystem class.
public FileSystem ();

Examples
Objects (Visual Basic)
FileSystem.FindInFiles
I n this Article

Overloads
Find​In​Files(​String, ​String, ​Boolean, ​Search​Option)
Returns a read-only collection of strings representing the
names of files containing the specified text.

Find​In​Files(​String, ​String, ​Boolean, ​Search​Option, ​String[])


Returns a read-only collection of strings representing the
names of files containing the specified text.

FindInFiles(String, String, Boolean, SearchOption)


This API is not CLS-compliant.
CLS- None.
compliant
alternative

Returns a read-only collection of strings representing the names of files containing the specified text.
public static System.Collections.ObjectModel.ReadOnlyCollection<string> FindInFiles (string
directory, string containsText, bool ignoreCase, Microsoft.VisualBasic.FileIO.SearchOption
searchType);

Parameters
directory String
The directory to be searched.
containsText String
The search text.
ignoreCase Boolean
True if the search should be case-sensitive; otherwise False . Default is True .
searchType SearchOption
Whether to include subfolders. Default is SearchOption.SearchTopLevelOnly .
Returns
ReadOnlyCollection<String>
Read-only collection of the names of files containing the specified text..
Exceptions
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 \.</code>).
ArgumentNullException
directory is Nothing or an empty string.
DirectoryNotFoundException
The specified directory does not exist.
IOException
The specified directory points to an existing file.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
The specified directory path contains a colon (:) or is in an invalid format.
SecurityException
The user lacks necessary permissions to view the path.
UnauthorizedAccessException
The user lacks necessary permissions.
Examples
This example searches the directory C: estDir for any files containing the string "sample string" and displays
the results in ListBox1 .
In order to work, the project must contain a ListBox named ListBox1 .
Remarks
An empty collection is returned if no files matching the specified pattern are found.
The following table lists an example of a task involving the My.Computer.FileSystem.FindInFiles method.

TO S EE

Search a directory for files containing a specific string Walkthrough: Manipulating Files and Directories in Visual Basic

FindInFiles(String, String, Boolean, SearchOption, String[])


This API is not CLS-compliant.
CLS- None.
compliant
alternative

Returns a read-only collection of strings representing the names of files containing the specified text.
public static System.Collections.ObjectModel.ReadOnlyCollection<string> FindInFiles (string
directory, string containsText, bool ignoreCase, Microsoft.VisualBasic.FileIO.SearchOption
searchType, string[] fileWildcards);

Parameters
directory String
The directory to be searched.
containsText String
The search text.
ignoreCase Boolean
True if the search should be case-sensitive; otherwise False . Default is True .
searchType SearchOption
Whether to include subfolders. Default is SearchOption.SearchTopLevelOnly .
fileWildcards String[]
Pattern to be matched.
Returns
ReadOnlyCollection<String>
Read-only collection of the names of files containing the specified text..
Exceptions
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 \.</code>).

ArgumentNullException
directory is Nothing or an empty string.
DirectoryNotFoundException
The specified directory does not exist.
IOException
The specified directory points to an existing file.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
The specified directory path contains a colon (:) or is in an invalid format.
SecurityException
The user lacks necessary permissions to view the path.
UnauthorizedAccessException
The user lacks necessary permissions.
Examples
This example searches the directory C: estDir for any files containing the string "sample string" and displays
the results in ListBox1 .

In order to work, the project must contain a ListBox named ListBox1 .


Remarks
An empty collection is returned if no files matching the specified pattern are found.
The following table lists an example of a task involving the My.Computer.FileSystem.FindInFiles method.

TO S EE

Search a directory for files containing a specific string Walkthrough: Manipulating Files and Directories in Visual Basic
FileSystem.GetDirectories
I n this Article

Overloads
Get​Directories(​String)
Returns a collection of strings representing the path names of
subdirectories within a directory.

Get​Directories(​String, ​Search​Option, ​String[])


Returns a collection of strings representing the path names of
subdirectories within a directory.

GetDirectories(String)
This API is not CLS-compliant.
CLS- None.
compliant
alternative

Returns a collection of strings representing the path names of subdirectories within a directory.
public static System.Collections.ObjectModel.ReadOnlyCollection<string> GetDirectories (string
directory);

Parameters
directory String
Name and path of directory.
Returns
ReadOnlyCollection<String>
Read-only collection of the path names of subdirectories within the specified directory..
Exceptions
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 \\.\).
ArgumentNullException
directory is Nothing or an empty string.
DirectoryNotFoundException
The specified directory does not exist.
IOException
The specified directory points to an existing file.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
SecurityException
The user lacks necessary permissions to view the path.
UnauthorizedAccessException
The user lacks necessary permissions.
Examples
The following example returns all the directories in the directory structure that contain the word Logs in their names
and adds them to ListBox1 .
This example requires that you have a ListBox named ListBox1 on your form.
Remarks
The following table lists an example of a task involving the My.Computer.FileSystem.GetDirectories method.

TO S EE

List subdirectories with a specific pattern How to: Find Subdirectories with a Specific Pattern in Visual
Basic

GetDirectories(String, SearchOption, String[])


This API is not CLS-compliant.
CLS- None.
compliant
alternative

Returns a collection of strings representing the path names of subdirectories within a directory.

public static System.Collections.ObjectModel.ReadOnlyCollection<string> GetDirectories (string


directory, Microsoft.VisualBasic.FileIO.SearchOption searchType, string[] wildcards);

Parameters
directory String
Name and path of directory.
searchType SearchOption
Whether to include subfolders. Default is SearchOption.SearchTopLevelOnly .

wildcards String[]
Pattern to match names.
Returns
ReadOnlyCollection<String>
Read-only collection of the path names of subdirectories within the specified directory.
Exceptions
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 \\.\).
ArgumentNullException
One or more of the specified wildcard characters is Nothing , an empty string, or contains only spaces.

DirectoryNotFoundException
The specified directory does not exist.
IOException
The specified directory points to an existing file.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
SecurityException
The user lacks necessary permissions to view the path.
UnauthorizedAccessException
The user lacks necessary permissions.
Examples
The following example returns all the directories in the directory structure that contain the word Logs in their names
and adds them to ListBox1 .

This example requires that you have a ListBox named ListBox1 on your form.
Remarks
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 SearchAllSubDirectories .
An empty collection is returned if no directories matching the specified pattern are found.
The following table lists an example of a task involving the My.Computer.FileSystem.GetDirectories method.

TO S EE

List subdirectories with a specific pattern How to: Find Subdirectories with a Specific Pattern in Visual
Basic
FileSystem.GetDirectoryInfo
I n this Article
Returns a DirectoryInfo object for the specified path.
public static System.IO.DirectoryInfo GetDirectoryInfo (string directory);

Parameters
directory String
String . Path of directory.

Returns
DirectoryInfo
DirectoryInfo object for the specified path.
Exceptions
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 \\.\).
ArgumentNullException
directory is Nothing or an empty string.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
The directory path contains a colon (:) or is in an invalid format.
SecurityException
The user lacks necessary permissions to view the path

Examples
This example gets a DirectoryInfo object for the directory C:\Documents and Settings and displays the directory's
creation time, last access time, and last write time.

Remarks
If the directory does not exist, an exception is not thrown until the first time a property on the DirectoryInfo object is
accessed.
FileSystem.GetDriveInfo
I n this Article
Returns a DriveInfo object for the specified drive.
public static System.IO.DriveInfo GetDriveInfo (string drive);

Parameters
drive String
Drive to be examined.
Returns
DriveInfo
DriveInfo object for the specified drive.
Exceptions
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 \\.\).
ArgumentNullException
drive is Nothing or an empty string.
PathTooLongException
The path exceeds the system-defined maximum length.
SecurityException
The user lacks necessary permissions to view the path

Examples
This example obtains a DriveInfo object for the C drive and uses it to display information about the drive.
For information on the different drive types, see DriveType.

Remarks
The DriveInfo class models a drive and provides methods and properties to query for drive information. Use DriveInfo
to determine what drives are available, and what type of drives they are. You can also query the property to determine
the capacity and available free space on the drive.
FileSystem.GetFileInfo
I n this Article
Returns a FileInfo object for the specified file.
public static System.IO.FileInfo GetFileInfo (string file);

Parameters
file String
Name and path of the file.
Returns
FileInfo
FileInfo object for the specified file
Exceptions
ArgumentException
The path name is malformed. For example, it contains invalid characters or is only white space. The file name has a
trailing slash mark.
ArgumentNullException
file is Nothing or an empty string.
NotSupportedException
The path contains a colon in the middle of the string.
PathTooLongException
The path is too long.
SecurityException
The user lacks necessary permissions.
UnauthorizedAccessException
The user lacks ACL (access control list) access to the file.

Examples
This example retrieves a System.IO.FileInfo object for the file MyLogFile.log and uses it to report the file's full name,
last access time, and length.

Remarks
An exception is not thrown if the file does not exist; rather, it will be thrown the first time the object's properties are
accessed.
The following table lists an example of a task involving the My.Computer.FileSystem.GetFileInfo method.
TO S EE

Determine a file's name and path How to: Parse File Paths in Visual Basic
FileSystem.GetFiles
I n this Article

Overloads
Get​Files(​String)
Returns a read-only collection of strings representing the
names of files within a directory.

Get​Files(​String, ​Search​Option, ​String[])


Returns a read-only collection of strings representing the
names of files within a directory.

GetFiles(String)
This API is not CLS-compliant.
CLS- None.
compliant
alternative

Returns a read-only collection of strings representing the names of files within a directory.
public static System.Collections.ObjectModel.ReadOnlyCollection<string> GetFiles (string directory);

Parameters
directory String
Directory to be searched.
Returns
ReadOnlyCollection<String>
Read-only collection of file names from the specified directory.
Exceptions
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 \\.\).
ArgumentNullException
directory is Nothing .
DirectoryNotFoundException
The directory to search does not exist.
IOException
directory points to an existing file.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
SecurityException
The user lacks necessary permissions to view the path.
UnauthorizedAccessException
The user lacks necessary permissions.
Examples
The following example returns all files in the directory and adds them to ListBox1 .
This example requires that you have a ListBox named ListBox1 on your form.

This example returns all files in the directory with the extension .txt and adds them to ListBox1 .
This example requires that you have a ListBox named ListBox1 on your form.
Remarks
An empty collection is returned if no files matching the specified pattern are found.
The following table lists examples of tasks involving the My.Computer.FileSystem.GetFiles method.

TO S EE

Get the collection of files in a directory How to: Get the Collection of Files in a Directory in Visual Basic

Find files with a specific pattern in a directory How to: Find Files with a Specific Pattern in Visual Basic

GetFiles(String, SearchOption, String[])


This API is not CLS-compliant.
CLS- None.
compliant
alternative

Returns a read-only collection of strings representing the names of files within a directory.
public static System.Collections.ObjectModel.ReadOnlyCollection<string> GetFiles (string directory,
Microsoft.VisualBasic.FileIO.SearchOption searchType, string[] wildcards);

Parameters
directory String
Directory to be searched.
searchType SearchOption
Whether to include subfolders. Default is SearchOption.SearchTopLevelOnly .
wildcards String[]
Pattern to be matched.
Returns
ReadOnlyCollection<String>
Read-only collection of file names from the specified directory.
Exceptions
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 \\.\).
ArgumentNullException
directory is Nothing .
DirectoryNotFoundException
The directory to search does not exist.
IOException
directory points to an existing file.

PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
SecurityException
The user lacks necessary permissions to view the path.
UnauthorizedAccessException
The user lacks necessary permissions.
Examples
The following example returns all files in the directory and adds them to ListBox1 .
This example requires that you have a ListBox named ListBox1 on your form.

This example returns all files in the directory with the extension .txt and adds them to ListBox1 .

This example requires that you have a ListBox named ListBox1 on your form.
Remarks
An empty collection is returned if no files matching the specified pattern are found.
The following table lists examples of tasks involving the My.Computer.FileSystem.GetFiles method.
TO S EE

Get the collection of files in a directory How to: Get the Collection of Files in a Directory in Visual Basic

Find files with a specific pattern in a directory How to: Find Files with a Specific Pattern in Visual Basic
FileSystem.GetName
I n this Article
Parses the file name out of the path provided.
public static string GetName (string path);

Parameters
path String
Required. Path to be parsed. String .
Returns
String
The file name from the specified path.

Examples
The following example parses a file path and returns the name of the file.
Replace the path C: estdirectory estfile with the path you wish to parse.

Remarks
This is a string operation; the FileSystem is not examined.
The GetName method ignores a slash mark occurring at the end of the path.
The following table lists an example of a task involving the My.Computer.FileSystem.GetFileName method.

TO S EE

Parse a file path How to: Parse File Paths in Visual Basic
FileSystem.GetParentPath
I n this Article
Returns the parent path of the provided path.
public static string GetParentPath (string path);

Parameters
path String
Path to be examined.
Returns
String
The parent path of the provided path.
Exceptions
ArgumentException
Path does not have a parent path because it is a root path.
ArgumentNullException
path is Nothing .
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.

Examples
This example gets the parent path for C:\Backups mp est .

Remarks
This is a string operation; the file system is not examined.
FileSystem.GetTempFileName
I n this Article
Creates a uniquely named zero-byte temporary file on disk and returns the full path of that file.
public static string GetTempFileName ();

Returns
String
String containing the full path of the temporary file.

Examples
This example creates a temp file and returns its path.

Remarks
This method can be used to create a temporary file.
FileSystem.MoveDirectory
I n this Article

Overloads
Move​Directory(​String, ​String)
Moves a directory from one location to another.

Move​Directory(​String, ​String, ​UI​Option)


Moves a directory from one location to another.

Move​Directory(​String, ​String, ​Boolean)


Moves a directory from one location to another.

Move​Directory(​String, ​String, ​UI​Option, ​UI​Cancel​Option)


Moves a directory from one location to another.

MoveDirectory(String, String)
Moves a directory from one location to another.
public static void MoveDirectory (string sourceDirectoryName, string destinationDirectoryName);

Parameters
sourceDirectoryName String
Path of the directory to be moved.
destinationDirectoryName String
Path of the directory to which the source directory is being moved.
Exceptions
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 \\.\).
ArgumentNullException
sourceDirectoryName or destinationDirectoryName is Nothing or an empty string.
DirectoryNotFoundException
The directory does not exist.
IOException
The source is a root directory or The source path and the target path are the same.
PathTooLongException
The path exceeds the system-defined maximum length.
InvalidOperationException
The operation is cyclic.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
SecurityException
The user lacks necessary permissions to view the path.
UnauthorizedAccessException
The user does not have required permission.
Examples
This example moves Directory1 inside Directory2 .

This example moves Directory1 inside Directory2 , overwriting the directory if it already exists.
Remarks
If an attempt is made to move a directory inside a directory that does not exist, the target structure will be created.

MoveDirectory(String, String, UIOption)


Moves a directory from one location to another.

public static void MoveDirectory (string sourceDirectoryName, string destinationDirectoryName,


Microsoft.VisualBasic.FileIO.UIOption showUI);

Parameters
sourceDirectoryName String
Path of the directory to be moved.
destinationDirectoryName String
Path of the directory to which the source directory is being moved.
showUI UIOption
Specifies whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs .

Exceptions
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 \\.\).
ArgumentNullException
sourceDirectoryName or destinationDirectoryName is Nothing or an empty string.

DirectoryNotFoundException
The directory does not exist.
IOException
The target directory already exists and overwrite is set to False .

PathTooLongException
The path exceeds the system-defined maximum length.
InvalidOperationException
The operation is cyclic.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
SecurityException
The user lacks necessary permissions to view the path.
UnauthorizedAccessException
The user does not have required permission.
Examples
This example moves Directory1 inside Directory2 .

This example moves Directory1 inside Directory2 , overwriting the directory if it already exists.
Remarks
If an attempt is made to move a directory inside a directory that does not exist, the target structure will be created.

MoveDirectory(String, String, Boolean)


Moves a directory from one location to another.
public static void MoveDirectory (string sourceDirectoryName, string destinationDirectoryName, bool
overwrite);

Parameters
sourceDirectoryName String
Path of the directory to be moved.
destinationDirectoryName String
Path of the directory to which the source directory is being moved.
overwrite Boolean
True if existing directories should be overwritten; otherwise False . Default is False .

Exceptions
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 \\.\).
ArgumentNullException
sourceDirectoryName or destinationDirectoryName is Nothing or an empty string.
DirectoryNotFoundException
The directory does not exist.
IOException
The target directory already exists and overwrite is set to False .

PathTooLongException
The path exceeds the system-defined maximum length.
InvalidOperationException
The operation is cyclic.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
SecurityException
The user lacks necessary permissions to view the path.
UnauthorizedAccessException
The user does not have required permission.
Examples
This example moves Directory1 inside Directory2 .

This example moves Directory1 inside Directory2 , overwriting the directory if it already exists.
Remarks
If an attempt is made to move a directory inside a directory that does not exist, the target structure will be created.

MoveDirectory(String, String, UIOption, UICancelOption)


Moves a directory from one location to another.
public static void MoveDirectory (string sourceDirectoryName, string destinationDirectoryName,
Microsoft.VisualBasic.FileIO.UIOption showUI, Microsoft.VisualBasic.FileIO.UICancelOption
onUserCancel);

Parameters
sourceDirectoryName String
Path of the directory to be moved.
destinationDirectoryName String
Path of the directory to which the source directory is being moved.
showUI UIOption
Specifies whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs .

onUserCancel UICancelOption
Specifies whether or not an exception is thrown when the user cancels the operation. Default is
UICancelOption.ThrowException .

Exceptions
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 \\.\).
ArgumentNullException
sourceDirectoryName or destinationDirectoryName is Nothing or an empty string.

DirectoryNotFoundException
The directory does not exist.
IOException
onUserCancel is set to ThrowException and a subdirectory of the file cannot be copied.

OperationCanceledException
onUserCancel is set to ThrowException , and the user cancels the operation, or the operation cannot be completed.

SecurityException
The user lacks necessary permissions to view the path.
PathTooLongException
The path exceeds the system-defined maximum length.
InvalidOperationException
The operation is cyclic.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
UnauthorizedAccessException
The user does not have required permission.
Examples
This example moves Directory1 inside Directory2 .
This example moves Directory1 inside Directory2 , overwriting the directory if it already exists.
Remarks
If an attempt is made to move a directory inside a directory that does not exist, the target structure will be created.
FileSystem.MoveFile
I n this Article

Overloads
Move​File(​String, ​String)
Moves a file to a new location.

Move​File(​String, ​String, ​UI​Option)


Moves a file to a new location.

Move​File(​String, ​String, ​Boolean)


Moves a file to a new location.

Move​File(​String, ​String, ​UI​Option, ​UI​Cancel​Option)


Moves a file to a new location.

MoveFile(String, String)
Moves a file to a new location.
public static void MoveFile (string sourceFileName, string destinationFileName);

Parameters
sourceFileName String
Path of the file to be moved.
destinationFileName String
Path of the directory into which the file should be moved.
Exceptions
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 \\.\); it ends with a trailing slash.
ArgumentNullException
destinationFileName is Nothing or an empty string.
FileNotFoundException
The source file is not valid or does not exist.
IOException
The file is in use by another process, or an I/O error occurs.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
SecurityException
The user lacks necessary permissions to view the path.
Examples
This example moves the file Test.txt from TestDir1 to TestDir2 .
This example moves the file Test.txt from TestDir1 to TestDir2 and renames it Test2.txt .
Remarks
If the target structure does not exist, it is created.
The MoveFile method preserves ACEs (Access Control Entries) only when moving the file within the same volume. This
includes inherited ACEs, which become direct ACEs when moved (direct ACEs take precedence over inherited ACEs). If a
file is moved between volumes, ACEs will not be copied.
The following table lists an example of a task involving the My.Computer.FileSystem.MoveFile method.

TO S EE

Move a file How to: Move a File in Visual Basic

MoveFile(String, String, UIOption)


Moves a file to a new location.

public static void MoveFile (string sourceFileName, string destinationFileName,


Microsoft.VisualBasic.FileIO.UIOption showUI);

Parameters
sourceFileName String
Path of the file to be moved.
destinationFileName String
Path of the directory into which the file should be moved.
showUI UIOption
Specifies whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs .

Exceptions
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 \\.\); it ends with a trailing slash.
ArgumentNullException
destinationFileName is Nothing or an empty string.
FileNotFoundException
The source file is not valid or does not exist.
IOException
The file is in use by another process, or an I/O error occurs.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
SecurityException
The user lacks necessary permissions to view the path.
Examples
This example moves the file Test.txt from TestDir1 to TestDir2 .

This example moves the file Test.txt from TestDir1 to TestDir2 and renames it Test2.txt .
Remarks
If the target structure does not exist, it is created.
The MoveFile method preserves ACEs (Access Control Entries) only when moving the file within the same volume. This
includes inherited ACEs, which become direct ACEs when moved (direct ACEs take precedence over inherited ACEs). If a
file is moved between volumes, ACEs will not be copied.
The following table lists an example of a task involving the My.Computer.FileSystem.MoveFile method.

TO S EE

Move a file How to: Move a File in Visual Basic

MoveFile(String, String, Boolean)


Moves a file to a new location.

public static void MoveFile (string sourceFileName, string destinationFileName, bool overwrite);

Parameters
sourceFileName String
Path of the file to be moved.
destinationFileName String
Path of the directory into which the file should be moved.
overwrite Boolean
True to overwrite existing files; otherwise False . Default is False .
Exceptions
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 \\.\); it ends with a trailing slash.
ArgumentNullException
destinationFileName is Nothing or an empty string.

FileNotFoundException
The source file is not valid or does not exist.
IOException
The file is in use by another process, or an I/O error occurs.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
SecurityException
The user lacks necessary permissions to view the path.
Examples
This example moves the file Test.txt from TestDir1 to TestDir2 .

This example moves the file Test.txt from TestDir1 to TestDir2 and renames it Test2.txt .
Remarks
If the target structure does not exist, it is created.
The MoveFile method preserves ACEs (Access Control Entries) only when moving the file within the same volume. This
includes inherited ACEs, which become direct ACEs when moved (direct ACEs take precedence over inherited ACEs). If a
file is moved between volumes, ACEs will not be copied.
The following table lists an example of a task involving the My.Computer.FileSystem.MoveFile method.

TO S EE

Move a file How to: Move a File in Visual Basic

MoveFile(String, String, UIOption, UICancelOption)


Moves a file to a new location.
public static void MoveFile (string sourceFileName, string destinationFileName,
Microsoft.VisualBasic.FileIO.UIOption showUI, Microsoft.VisualBasic.FileIO.UICancelOption
onUserCancel);

Parameters
sourceFileName String
Path of the file to be moved.
destinationFileName String
Path of the directory into which the file should be moved.
showUI UIOption
Specifies whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs .

onUserCancel UICancelOption
Specifies whether or not an exception is thrown when the user cancels the operation. Default is
UICancelOption.ThrowException .

Exceptions
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 \\.\); it ends with a trailing slash.
ArgumentNullException
destinationFileName is Nothing or an empty string.

FileNotFoundException
The source file is not valid or does not exist.
IOException
The file is in use by another process, or an I/O error occurs.
OperationCanceledException
onUserCancel is set to ThrowException , and either the user has cancelled the operation or an unspecified I/O error
occurs.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
SecurityException
The user lacks necessary permissions to view the path.
Examples
This example moves the file Test.txt from TestDir1 to TestDir2 .
This example moves the file Test.txt from TestDir1 to TestDir2 and renames it Test2.txt .
Remarks
If the target structure does not exist, it is created.
The MoveFile method preserves ACEs (Access Control Entries) only when moving the file within the same volume. This
includes inherited ACEs, which become direct ACEs when moved (direct ACEs take precedence over inherited ACEs). If a
file is moved between volumes, ACEs will not be copied.
The following table lists an example of a task involving the My.Computer.FileSystem.MoveFile method.

TO S EE

Move a file How to: Move a File in Visual Basic


FileSystem.OpenTextFieldParser
I n this Article

Overloads
Open​Text​Field​Parser(​String, ​String[])
The OpenTextFieldParser method allows you to create a
TextFieldParser object, which provides a way to easily and
efficiently parse structured text files, such as logs. The
TextFieldParser object can be used to read both
delimited and fixed-width files.

Open​Text​Field​Parser(​String)
The OpenTextFieldParser method allows you to create a
TextFieldParser object, which provides a way to easily and
efficiently parse structured text files, such as logs. The
TextFieldParser object can be used to read both
delimited and fixed-width files.

Open​Text​Field​Parser(​String, ​Int32[])
The OpenTextFieldParser method allows you to create a
TextFieldParser object, which provides a way to easily and
efficiently parse structured text files, such as logs. The
TextFieldParser object can be used to read both
delimited and fixed-width files.

OpenTextFieldParser(String, String[])
The OpenTextFieldParser method allows you to create a TextFieldParser object, which provides a way to easily and
efficiently parse structured text files, such as logs. The TextFieldParser object can be used to read both delimited and
fixed-width files.
public static Microsoft.VisualBasic.FileIO.TextFieldParser OpenTextFieldParser (string file,
string[] delimiters);

Parameters
file String
The file to be opened with the TextFieldParser .
delimiters String[]
Delimiters for the fields.
Returns
TextFieldParser
TextFieldParser to read the specified file.
Exceptions
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 \\.\); it ends with a trailing slash.
ArgumentNullException
file is Nothing .
FileNotFoundException
The file does not exist.
IOException
The file is in use by another process, or an I/O error occurs.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
MalformedLineException
A row cannot be parsed using the specified format. The exception message specifies the line causing the exception,
while the ErrorLine property is assigned the text contained in the line.
SecurityException
The user lacks necessary permissions to view the path.
Examples
This example opens the TextFieldParser.reader and uses it to read from C: estFolder1 est1.txt .

Remarks
The following table lists examples of tasks involving the My.Computer.FileSystem.OpenTextFieldParser method.

TO S EE

Read from a delimited text file How to: Read From Comma-Delimited Text Files in Visual Basic

Read from a fixed-width text file How to: Read From Fixed-width Text Files in Visual Basic

Read from a text file with multiple formats How to: Read From Text Files with Multiple Formats in Visual
Basic

OpenTextFieldParser(String)
The OpenTextFieldParser method allows you to create a TextFieldParser object, which provides a way to easily and
efficiently parse structured text files, such as logs. The TextFieldParser object can be used to read both delimited and
fixed-width files.
public static Microsoft.VisualBasic.FileIO.TextFieldParser OpenTextFieldParser (string file);

Parameters
file String
The file to be opened with the TextFieldParser .
Returns
TextFieldParser
TextFieldParser to read the specified file.
Exceptions
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 \\.\); it ends with a trailing slash.
ArgumentNullException
file is Nothing .
FileNotFoundException
The file does not exist.
IOException
The file is in use by another process, or an I/O error occurs.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
MalformedLineException
A row cannot be parsed using the specified format. The exception message specifies the line causing the exception,
while the ErrorLine property is assigned the text contained in the line.
SecurityException
The user lacks necessary permissions to view the path.
Examples
This example opens the TextFieldParser.reader and uses it to read from C: estFolder1 est1.txt .

Remarks
The following table lists examples of tasks involving the My.Computer.FileSystem.OpenTextFieldParser method.

TO S EE

Read from a delimited text file How to: Read From Comma-Delimited Text Files in Visual Basic

Read from a fixed-width text file How to: Read From Fixed-width Text Files in Visual Basic

Read from a text file with multiple formats How to: Read From Text Files with Multiple Formats in Visual
Basic

OpenTextFieldParser(String, Int32[])
The OpenTextFieldParser method allows you to create a TextFieldParser object, which provides a way to easily and
efficiently parse structured text files, such as logs. The TextFieldParser object can be used to read both delimited and
fixed-width files.

public static Microsoft.VisualBasic.FileIO.TextFieldParser OpenTextFieldParser (string file, int[]


fieldWidths);

Parameters
file String
The file to be opened with the TextFieldParser .

fieldWidths Int32[]
Widths of the fields.
Returns
TextFieldParser
TextFieldParser to read the specified file.
Exceptions
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 \\.\); it ends with a trailing slash.
ArgumentNullException
file is Nothing .

FileNotFoundException
The file does not exist.
IOException
The file is in use by another process, or an I/O error occurs.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
MalformedLineException
A row cannot be parsed using the specified format. The exception message specifies the line causing the exception,
while the ErrorLine property is assigned the text contained in the line.
SecurityException
The user lacks necessary permissions to view the path.
Examples
This example opens the TextFieldParser.reader and uses it to read from C: estFolder1 est1.txt .

Remarks
The following table lists examples of tasks involving the My.Computer.FileSystem.OpenTextFieldParser method.

TO S EE

Read from a delimited text file How to: Read From Comma-Delimited Text Files in Visual Basic

Read from a fixed-width text file How to: Read From Fixed-width Text Files in Visual Basic

Read from a text file with multiple formats How to: Read From Text Files with Multiple Formats in Visual
Basic
FileSystem.OpenTextFileReader
I n this Article

Overloads
Open​Text​File​Reader(​String)
Opens a StreamReader object to read from a file.

Open​Text​File​Reader(​String, ​Encoding)
Opens a StreamReader object to read from a file.

OpenTextFileReader(String)
Opens a StreamReader object to read from a file.
public static System.IO.StreamReader OpenTextFileReader (string file);

Parameters
file String
File to be read.
Returns
StreamReader
StreamReader object to read from the file
Exceptions
ArgumentException
The file name ends with a backslash (\).
FileNotFoundException
The specified file cannot be found.
SecurityException
The user lacks necessary permissions to read from the file.
Examples
This example opens the file Testfile.txt , reads a line from it, and displays the line in a MessageBox .
Remarks
Only text files can be read with a StreamReader.
The following table lists an example of a task involving the My.Computer.FileSystem.OpenTextFileReader method.

TO S EE

Open a file with a StreamReader How to: Read Text from Files with a StreamReader (Visual
Basic)
OpenTextFileReader(String, Encoding)
Opens a StreamReader object to read from a file.
public static System.IO.StreamReader OpenTextFileReader (string file, System.Text.Encoding
encoding);

Parameters
file String
File to be read.
encoding Encoding
The encoding to use for the file contents. Default is ASCII.
Returns
StreamReader
StreamReader object to read from the file
Exceptions
ArgumentException
The file name ends with a backslash (\).
FileNotFoundException
The specified file cannot be found.
SecurityException
The user lacks necessary permissions to read from the file.
Examples
This example opens the file Testfile.txt , reads a line from it, and displays the line in a MessageBox .
Remarks
Only text files can be read with a StreamReader.
The following table lists an example of a task involving the My.Computer.FileSystem.OpenTextFileReader method.

TO S EE

Open a file with a StreamReader How to: Read Text from Files with a StreamReader (Visual
Basic)
FileSystem.OpenTextFileWriter
I n this Article

Overloads
Open​Text​File​Writer(​String, ​Boolean)
Opens a StreamWriter object to write to the specified file.

Open​Text​File​Writer(​String, ​Boolean, ​Encoding)


Opens a StreamWriter to write to the specified file.

OpenTextFileWriter(String, Boolean)
Opens a StreamWriter object to write to the specified file.
public static System.IO.StreamWriter OpenTextFileWriter (string file, bool append);

Parameters
file String
File to be written to.
append Boolean
True to append to the contents of the file; False to overwrite the contents of the file. Default is False .
Returns
StreamWriter
StreamWriter object to write to the specified file.
Exceptions
ArgumentException
The file name ends with a trailing slash.
Examples
This example opens a StreamWriter 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.
Remarks
The OpenTextFileWriter method opens and initializes a stream for a file and then returns the StreamWriter object for
that stream. You can write to the steam as many times as necessary and then close it when you are finished.
Note

You must call the Close method on the StreamWriter object to make sure that all data is correctly written to the
underlying stream.
If you are writing only a few strings to a file, it might be simpler to use the WriteAllText method.
The following table lists an example of a task involving the My.Computer.FileSystem.OpenTextFileWriter method.
TO S EE

Write text to a file with a StreamWriter How to: Write Text to Files with a StreamWriter in Visual Basic

OpenTextFileWriter(String, Boolean, Encoding)


Opens a StreamWriter to write to the specified file.
public static System.IO.StreamWriter OpenTextFileWriter (string file, bool append,
System.Text.Encoding encoding);

Parameters
file String
File to be written to.
append Boolean
True to append to the contents in the file; False to overwrite the contents of the file. Default is False .

encoding Encoding
Encoding to be used in writing to the file. Default is ASCII.
Returns
StreamWriter
StreamWriter object to write to the specified file.
Exceptions
ArgumentException
The file name ends with a trailing slash.
Examples
This example opens a StreamWriter 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.
Remarks
The OpenTextFileWriter method opens and initializes a stream for a file and then returns the StreamWriter object for
that stream. You can write to the steam as many times as necessary and then close it when you are finished.
Note

You must call the Close method on the StreamWriter object to make sure that all data is correctly written to the
underlying stream.
If you are writing only a few strings to a file, it might be simpler to use the WriteAllText method.
The following table lists an example of a task involving the My.Computer.FileSystem.OpenTextFileWriter method.

TO S EE

Write text to a file with a StreamWriter How to: Write Text to Files with a StreamWriter in Visual Basic
FileSystem.ReadAllBytes
I n this Article
Returns the contents of a file as a byte array.
public static byte[] ReadAllBytes (string file);

Parameters
file String
File to be read.
Returns
Byte[]
Byte array containing the contents of the file.
Exceptions
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 \\.\); it ends with a trailing slash.
ArgumentNullException
file is Nothing .
FileNotFoundException
The file does not exist.
IOException
The file is in use by another process, or an I/O error occurs.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
OutOfMemoryException
There is not enough memory to write the string to buffer.
SecurityException
The user lacks necessary permissions to view the path.

Examples
This example reads from the file C:/Documents and Settings/selfportrait.jpg.

Remarks
The ReadAllBytes method of the My.Computer.FileSystem object allows you to read from a binary file. The contents
of the file are returned as a byte array.
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 following table lists an example of a task involving the My.Computer.FileSystem.ReadAllBytes method.

TO S EE

Read from a binary file How to: Read From Binary Files in Visual Basic
FileSystem.ReadAllText
I n this Article

Overloads
Read​All​Text(​String)
Returns the contents of a text file as a String .

Read​All​Text(​String, ​Encoding)
Returns the contents of a text file as a String .

ReadAllText(String)
Returns the contents of a text file as a String .

public static string ReadAllText (string file);

Parameters
file String
Name and path of the file to read.
Returns
String
String containing the contents of the file.
Exceptions
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 \\.\); it ends with a trailing slash.
ArgumentNullException
file is Nothing .
FileNotFoundException
The file does not exist.
IOException
The file is in use by another process, or an I/O error occurs.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
OutOfMemoryException
There is not enough memory to write the string to buffer.
SecurityException
The user lacks necessary permissions to view the path.
Examples
This example reads the contents of Test.txt into a string and then displays it in a message box.
This example reads the contents of the ASCII file Test.txt into a string and then displays it in a message box.
Remarks
The ReadAllText method of the My.Computer.FileSystem object allows you to read from a text file. The contents of
the file are returned as a string.
The file encoding can be specified if the contents of the file are in an encoding such as ASCII or UTF-8. If you are
reading from a file with extended characters, you need to specify the file encoding using another overload of the
ReadAllText method.
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 following table lists an example of a task involving the My.Computer.FileSystem.ReadAllText method.

TO S EE

Read from a text file How to: Read From Text Files in Visual Basic

ReadAllText(String, Encoding)
Returns the contents of a text file as a String .

public static string ReadAllText (string file, System.Text.Encoding encoding);

Parameters
file String
Name and path of the file to read.
encoding Encoding
Character encoding to use in reading the file. Default is UTF-8.
Returns
String
String containing the contents of the file.

Exceptions
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 \\.\); it ends with a trailing slash.
ArgumentNullException
file is Nothing .

FileNotFoundException
The file does not exist.
IOException
The file is in use by another process, or an I/O error occurs.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
OutOfMemoryException
There is not enough memory to write the string to buffer.
SecurityException
The user lacks necessary permissions to view the path.
Examples
This example reads the contents of Test.txt into a string and then displays it in a message box.
This example reads the contents of the ASCII file Test.txt into a string and then displays it in a message box.
Remarks
The ReadAllText method of the My.Computer.FileSystem object allows you to read from a text file. The contents of
the file are returned as a string.
The file encoding can be specified if the contents of the file are in an encoding such as ASCII or UTF-8. If you are
reading from a file with extended characters, you need to specify the file encoding.
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 following table lists an example of a task involving the My.Computer.FileSystem.ReadAllText method.

TO S EE

Read from a text file How to: Read From Text Files in Visual Basic
FileSystem.RenameDirectory
I n this Article
Renames a directory.
public static void RenameDirectory (string directory, string newName);

Parameters
directory String
Path and name of directory to be renamed.
newName String
New name for directory.
Exceptions
ArgumentException
newName contains path information.

ArgumentNullException
directory is Nothing .
-or-
newName is Nothing or an empty string.
DirectoryNotFoundException
The directory does not exist.
IOException
There is an existing file or directory with the name specified in newName .
PathTooLongException
The path exceeds 248 characters.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
SecurityException
The user lacks necessary permissions to view the path.
UnauthorizedAccessException
The user does not have required permission.

Examples
This example renames the Test directory to SecondTest .

Remarks
This method cannot be used to move a directory; use the MoveDirectory method to move and rename the directory.
FileSystem.RenameFile
I n this Article
Renames a file.
public static void RenameFile (string file, string newName);

Parameters
file String
File to be renamed.
newName String
New name of file.
Exceptions
ArgumentException
newName contains path information or ends with a backslash (\).

ArgumentNullException
file is Nothing .
-or-
newName is Nothing or an empty string.
FileNotFoundException
The directory does not exist.
IOException
There is an existing file or directory with the name specified in newName .
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
SecurityException
The user lacks necessary permissions to view the path.
UnauthorizedAccessException
The user does not have required permission.

Examples
This example renames the file Test.txt to SecondTest.txt .
Change " C: est.txt " to the path and file name of the file that you want to rename.
Remarks
This method cannot be used to move a file; use the MoveFile method to move and rename the file.
The following table lists an example of a task involving the My.Computer.FileSystem.RenameFile method.

TO S EE

Rename a file How to: Rename a File in Visual Basic


FileSystem.WriteAllBytes
I n this Article
Writes data to a binary file.
public static void WriteAllBytes (string file, byte[] data, bool append);

Parameters
file String
Path and name of the file to be written to.
data Byte[]
Data to be written to the file.
append Boolean
True to append to the file contents; False to overwrite the file contents. Default is False .
Exceptions
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 \\.\); it ends with a trailing slash.
ArgumentNullException
file is Nothing .
FileNotFoundException
The file does not exist.
IOException
The file is in use by another process, or an I/O error occurs.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
OutOfMemoryException
There is not enough memory to write the string to buffer.
SecurityException
The user lacks necessary permissions to view the path.

Examples
This example appends the data array CustomerData to the file CollectedData .
Remarks
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 is created.
Note

The WriteAllBytes method opens a file, writes to it, and then closes it. Code that uses the WriteAllBytes method is
simpler than code that uses a BinaryWriter object. However, if you are adding data to a file using a loop, a BinaryWriter
object can provide better performance because you only have to open and close the file once.
The following table lists an example of a task involving the My.Computer.FileSystem.WriteAllBytes method.

TO S EE

Write to a binary file How to: Write to Binary Files in Visual Basic
FileSystem.WriteAllText
I n this Article

Overloads
Write​All​Text(​String, ​String, ​Boolean)
Writes text to a file.

Write​All​Text(​String, ​String, ​Boolean, ​Encoding)


Writes text to a file.

WriteAllText(String, String, Boolean)


Writes text to a file.
public static void WriteAllText (string file, string text, bool append);

Parameters
file String
File to be written to.
text String
Text to be written to file.
append Boolean
True to append to the contents of the file; False to overwrite the contents of the file.
Exceptions
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 \\.\); it ends with a trailing slash.
ArgumentNullException
file is Nothing .
FileNotFoundException
The file does not exist.
IOException
The file is in use by another process, or an I/O error occurs.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
OutOfMemoryException
There is not enough memory to write the string to buffer.
SecurityException
The user lacks necessary permissions to view the path.
Examples
This example writes the line "This is new text to be added." to the file Test.txt , overwriting any existing text in
the file.
This example writes the names of the files in the Documents and Settings folder to FileList.txt , inserting a
carriage return between each for better readability.
Remarks
The UTF-8 encoding is used to write to the file. To specify a different encoding, use a different overload of the
WriteAllText method.
If the specified file does not exist, it is created.
If the specified encoding does not match the existing encoding of the file, the specified coding is ignored.
Note

The WriteAllText method opens a file, writes to it, and then closes it. Code that uses the WriteAllText method is
simpler than code that uses a StreamWriter object. However, if you are adding strings to a file by using a loop, a
StreamWriter object can provide better performance because you only have to open and close the file one time. For
more information, see the OpenTextFileWriter method.
The following table lists examples of tasks involving the My.Computer.FileSystem.WriteAllText method.

TO S EE

Write text to a file How to: Write Text to Files in Visual Basic

Append text to a file How to: Append to Text Files in Visual Basic

WriteAllText(String, String, Boolean, Encoding)


Writes text to a file.

public static void WriteAllText (string file, string text, bool append, System.Text.Encoding
encoding);

Parameters
file String
File to be written to.
text String
Text to be written to file.
append Boolean
True to append to the contents of the file; False to overwrite the contents of the file.
encoding Encoding
What encoding to use when writing to file.
Exceptions
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 \\.\); it ends with a trailing slash.
ArgumentNullException
file is Nothing .

FileNotFoundException
The file does not exist.
IOException
The file is in use by another process, or an I/O error occurs.
PathTooLongException
The path exceeds the system-defined maximum length.
NotSupportedException
A file or directory name in the path contains a colon (:) or is in an invalid format.
OutOfMemoryException
There is not enough memory to write the string to buffer.
SecurityException
The user lacks necessary permissions to view the path.
Examples
This example writes the line "This is new text to be added." to the file Test.txt , overwriting any existing text in
the file.
This example writes the names of the files in the Documents and Settings folder to FileList.txt , inserting a
carriage return between each for better readability.
Remarks
If the specified file does not exist, it is created.
If the specified encoding does not match the existing encoding of the file, the specified coding is ignored.
Note

The WriteAllText method opens a file, writes to it, and then closes it. Code that uses the WriteAllText method is
simpler than code that uses a StreamWriter object. However, if you are adding strings to a file by using a loop, a
StreamWriter object can provide better performance because you only have to open and close the file one time. For
more information, see the OpenTextFileWriter method.
The following table lists examples of tasks involving the My.Computer.FileSystem.WriteAllText method.
TO S EE

Write text to a file How to: Write Text to Files in Visual Basic

Append text to a file How to: Append to Text Files in Visual Basic
MalformedLineException Class
The exception that is thrown when the ReadFields() method cannot parse a row using the specified format.

D eclaration
public class MalformedLineException : Exception

I nheritance H ierarchy
Object
Exception

Remarks
Check to ensure that the TextFieldType and Delimiter parameters are defined properly.

If the ReadFields method cannot parse a row using the specified format, the MalformedLineException exception is
thrown. The exception contains the line number of the malformed line.

Constructors
MalformedLineException()

Initializes a new instance of the MalformedLineException class.


D eclaration
public MalformedLineException ();

MalformedLineException(String)

Initializes a new instance of the MalformedLineException class with a specified error message.
D eclaration
public MalformedLineException (string message);

Parameters
message String
A message that describes the error.

MalformedLineException(SerializationInfo, StreamingContext)

Initializes a new instance of the MalformedLineException class with serialized data.


D eclaration
protected MalformedLineException (System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context);

Parameters
info SerializationInfo
The SerializationInfo object that holds the serialized object data about the exception being thrown.

context StreamingContext
The StreamingContext structure that contains contextual information about the source or destination.

MalformedLineException(String, Exception)

Initializes a new instance of the MalformedLineException class with a specified error message and a reference to
the inner exception that is the cause of this exception.
D eclaration
public MalformedLineException (string message, Exception innerException);

Parameters
message String
A String describing the error.

innerException Exception
The Exception object that is the cause of the current exception. If the InnerException parameter is not a null reference ( Nothing in Visual
Basic), the current exception is raised in a catch block that handles the inner exception.

MalformedLineException(String, Int64)

Initializes a new instance of the MalformedLineException class with a specified error message and a line number.
D eclaration
public MalformedLineException (string message, long lineNumber);

Parameters
message String
The message for the exception.

lineNumber Int64
The line number of the malformed line.

MalformedLineException(String, Int64, Exception)

Initializes a new instance of the MalformedLineException class with a specified error message, a line number, and a
reference to the inner exception that is the cause of this exception.
D eclaration
public MalformedLineException (string message, long lineNumber, Exception innerException);

Parameters
message String
The message for the exception.

lineNumber Int64
The line number of the malformed line.

innerException Exception
The Exception that is the cause of the current exception. If the InnerException parameter is not a null reference ( Nothing in Visual Basic),
the current exception is raised in a catch block that handles the inner exception.

Properties
LineNumber

Gets the line number of the malformed line.


D eclaration
public long LineNumber { get; set; }

P roperty Value
Int64
The line number of the malformed line.

Methods
GetObjectData(SerializationInfo, StreamingContext)

Sets the SerializationInfo object with information about the exception.


D eclaration
[System.Security.SecurityCritical]
public override void GetObjectData (System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context);

Parameters
info SerializationInfo
The SerializationInfo object that holds the serialized object data about the exception being thrown.

context StreamingContext
The StreamingContext structure that contains contextual information about the source or destination.

ToString()

Creates and returns a string representation of the current exception.


D eclaration
public override string ToString ();

Returns
String
A string representation of the current exception.
MalformedLineException.GetObjectData
I n this Article
Sets the SerializationInfo object with information about the exception.
[System.Security.SecurityCritical]
public override void GetObjectData (System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context);

Parameters
info SerializationInfo
The SerializationInfo object that holds the serialized object data about the exception being thrown.
context StreamingContext
The StreamingContext structure that contains contextual information about the source or destination.
Attributes SecurityCriticalAttribute

Remarks
This method sets a SerializationInfo object with all the exception object data targeted for serialization. During
deserialization, the exception is reconstituted from the SerializationInfo transmitted over the stream.
MalformedLineException.LineNumber
I n this Article
Gets the line number of the malformed line.
public long LineNumber { get; set; }

Returns
Int64
The line number of the malformed line.

Remarks
If the ReadFields method cannot parse a row using the specified format, the MalformedLineException exception is
thrown. The exception contains the line number of the malformed line.
MalformedLineException
I n this Article

Overloads
Malformed​Line​Exception()
Initializes a new instance of the MalformedLineException class.

Malformed​Line​Exception(​String)
Initializes a new instance of the MalformedLineException class
with a specified error message.

Malformed​Line​Exception(​Serialization​Info, ​Streaming​Context)
Initializes a new instance of the MalformedLineException class
with serialized data.

Malformed​Line​Exception(​String, ​Exception)
Initializes a new instance of the MalformedLineException class
with a specified error message and a reference to the inner
exception that is the cause of this exception.

Malformed​Line​Exception(​String, ​Int64)
Initializes a new instance of the MalformedLineException class
with a specified error message and a line number.

Malformed​Line​Exception(​String, ​Int64, ​Exception)


Initializes a new instance of the MalformedLineException class
with a specified error message, a line number, and a reference
to the inner exception that is the cause of this exception.

MalformedLineException()
Initializes a new instance of the MalformedLineException class.
public MalformedLineException ();

Remarks
The exception indicates that the ReadFields method cannot parse a row using the specified format.
The following table shows the initial property values for an instance of MalformedLineException.

PR O PER T Y V ALU E

InnerException A null reference ( Nothing in Visual Basic).

Message The localized error message string.

MalformedLineException(String)
Initializes a new instance of the MalformedLineException class with a specified error message.
public MalformedLineException (string message);

Parameters
message String
A message that describes the error.
Remarks
The content of the message parameter is intended to be understood by humans. The caller of this constructor is
required to ensure that this string has been localized for the current system culture.
MalformedLineException inherits from the Exception class. This constructor sets the properties of the Exception object
as shown in the following table.

PR O PER T Y V ALU E

InnerException A null reference ( Nothing in Visual Basic)

Message The message string.

MalformedLineException(SerializationInfo, StreamingContext)
Initializes a new instance of the MalformedLineException class with serialized data.

protected MalformedLineException (System.Runtime.Serialization.SerializationInfo info,


System.Runtime.Serialization.StreamingContext context);

Parameters
info SerializationInfo
The SerializationInfo object that holds the serialized object data about the exception being thrown.
context StreamingContext
The StreamingContext structure that contains contextual information about the source or destination.
Remarks
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream.

MalformedLineException(String, Exception)
Initializes a new instance of the MalformedLineException class with a specified error message and a reference to the
inner exception that is the cause of this exception.

public MalformedLineException (string message, Exception innerException);

Parameters
message String
A String describing the error.
innerException Exception
The Exception object that is the cause of the current exception. If the InnerException parameter is not a null reference (
Nothing in Visual Basic), the current exception is raised in a catch block that handles the inner exception.

Remarks
The content of the message parameter is intended to be understood by humans. The caller of this constructor is
required to ensure that this string has been localized for the current system culture.
An exception that is thrown as a direct result of a previous exception should include a reference to the previous
exception in the InnerException property. The InnerException property returns the same value that is passed into the
constructor, or a null reference if the InnerException property does not supply the inner exception value to the
constructor.
The following table shows the initial property values for an instance of ApplicationException.

PR O PER T Y V ALU E

InnerException The innerException reference.

Message The message string.

MalformedLineException(String, Int64)
Initializes a new instance of the MalformedLineException class with a specified error message and a line number.
public MalformedLineException (string message, long lineNumber);

Parameters
message String
The message for the exception.
lineNumber Int64
The line number of the malformed line.
Remarks
The content of the message parameter is intended to be understood by humans. The caller of this constructor is
required to ensure that this string has been localized for the current system culture. The lineNumber parameter
initializes the LineNumber property.
MalformedLineException inherits from the Exception. This constructor sets the properties of the Exception object as
shown in the following table.

PR O PER T Y V ALU E

InnerException A null reference ( Nothing in Visual Basic)

Message The message string.

MalformedLineException(String, Int64, Exception)


Initializes a new instance of the MalformedLineException class with a specified error message, a line number, and a
reference to the inner exception that is the cause of this exception.

public MalformedLineException (string message, long lineNumber, Exception innerException);

Parameters
message String
The message for the exception.
lineNumber Int64
The line number of the malformed line.
innerException Exception
The Exception that is the cause of the current exception. If the InnerException parameter is not a null reference (
Nothing in Visual Basic), the current exception is raised in a catch block that handles the inner exception.

Remarks
The content of the message parameter is intended to be understood by humans. The caller of this constructor is
required to ensure that this string has been localized for the current system culture. The lineNumber parameter
initializes the LineNumber property.
An exception that is thrown as a direct result of a previous exception should include a reference to the previous
exception in the InnerException property. The InnerException property returns the same value that is passed into the
constructor, or a null reference if the InnerException property does not supply the inner exception value to the
constructor.
The following table shows the initial property values for an instance of ApplicationException.

PR O PER T Y V ALU E

InnerException The innerException reference.

Message The message string.


MalformedLineException.ToString
I n this Article
Creates and returns a string representation of the current exception.
public override string ToString ();

Returns
String
A string representation of the current exception.

Remarks
ToString returns a representation of the current exception that is intended to be understood by humans. Where the
exception contains culture-sensitive data, the string representation returned by ToString is required to take into account
the current system culture. Although there are no exact requirements for the format of the returned string, it should
attempt to reflect the value of the object as perceived by the user.
The default implementation of ToString obtains the name of the class that threw the current exception, the message,
the result of calling ToString on the inner exception, the result of calling StackTrace, and the line number of the
malformed line If any of these members is a null reference ( Nothing in Visual Basic), its value is not included in the
returned string.
If there is no error message or if it is an empty string (""), then no error message is returned. The name of the inner
exception and the stack trace are returned only if they are not a null reference ( Nothing in Visual Basic).
This method overrides System.Exception.ToString.
RecycleOption Enum
Specifies whether a file should be deleted permanently or placed in the Recycle Bin.

D eclaration
public enum RecycleOption

I nheritance H ierarchy
Object
ValueType
Enum

Remarks
This enumeration is used with the DeleteDirectory and DeleteFile methods.
To protect users against accidental deletion of important files, the Recycle Bin collects deleted files and provides a
method for restoring those files. You must explicitly delete the files from the Recycle Bin to make the deletion
permanent. Until the files are deleted from the Recycle Bin, the disk space occupied by those files is unavailable for
other uses.
Sometimes it is beneficial to bypass the Recycle Bin, especially if you are deleting a large number of files (or a smaller
number of very large files) that you are sure are no longer needed, and you want to reclaim the disk space.

Fields
DeletePermanently Delete the file or directory permanently. Default.

SendToRecycleBin Send the file or directory to the Recycle Bin.


RecycleOption.DeletePermanently
I n this Article
Delete the file or directory permanently. Default.
DeletePermanently

Returns
RecycleOption
RecycleOption.SendToRecycleBin
I n this Article
Send the file or directory to the Recycle Bin.
SendToRecycleBin

Returns
RecycleOption
SearchOption Enum
Specifies whether to search all or only top-level directories.

D eclaration
public enum SearchOption

I nheritance H ierarchy
Object
ValueType
Enum

Remarks
This enumeration is used with the GetFiles, GetDirectories, and FindInFiles methods.

Fields
SearchAllSubDirectories Search the specified directory and all subdirectories within it. Default.

SearchTopLevelOnly Search only the specified directory and exclude subdirectories.


SearchOption.SearchAllSubDirectories
I n this Article
Search the specified directory and all subdirectories within it. Default.
SearchAllSubDirectories

Returns
SearchOption
SearchOption.SearchTopLevelOnly
I n this Article
Search only the specified directory and exclude subdirectories.
SearchTopLevelOnly

Returns
SearchOption
SpecialDirectories Class
Provides properties for accessing commonly referenced directories.

D eclaration
public class SpecialDirectories

I nheritance H ierarchy
Object

Remarks
If the path for the referenced directory is empty, usually due to the operating system not supporting the directory, a
DirectoryNotFoundException exception is thrown.
No backslash (\) appears at the end of the path.
The following table lists examples of tasks involving the My.Computer.FileSystem.SpecialDirectories object.

TO S EE

Read from the MyDocuments directory How to: Retrieve the Contents of the My Documents Directory

Availability by P roject Type


PR O JECT T YPE AV AIL AB LE

Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes

Constructors
SpecialDirectories()

Returns an instance of the SpecialDirectories class.


D eclaration
public SpecialDirectories ();
Properties
AllUsersApplicationData

Gets a path name pointing to the Application Data directory for the all users.
D eclaration
public static string AllUsersApplicationData { get; }

P roperty Value
String
The path to the Application Data directory for the all users.

CurrentUserApplicationData

Gets a path name pointing to the Application Data directory for the current user.
D eclaration
public static string CurrentUserApplicationData { get; }

P roperty Value
String
The path to the Application Data directory for the current user.

Desktop

Gets a path name pointing to the Desktop directory.


D eclaration
public static string Desktop { get; }

P roperty Value
String
The path to the Desktop directory.

MyDocuments

Gets a path name pointing to the My Documents directory.


D eclaration
public static string MyDocuments { get; }

P roperty Value
String
The path to the My Documents directory.
MyMusic

Gets a path name pointing to the My Music directory.


D eclaration
public static string MyMusic { get; }

P roperty Value
String
The path to the My Music directory.

MyPictures

Gets a path name pointing to the My Pictures directory.


D eclaration
public static string MyPictures { get; }

P roperty Value
String
The path to the My Pictures directory.

ProgramFiles

Gets a path pointing to the Program Files directory.


D eclaration
public static string ProgramFiles { get; }

P roperty Value
String
The path to the Program Files directory.

Programs

Gets a path name pointing to the Programs directory.


D eclaration
public static string Programs { get; }

P roperty Value
String
The path to the Programs directory.

Temp
Gets a path name pointing to the Temp directory.
D eclaration
public static string Temp { get; }

P roperty Value
String
The path to the Temp directory.
SpecialDirectories.AllUsersApplicationData
I n this Article
Gets a path name pointing to the Application Data directory for the all users.
public static string AllUsersApplicationData { get; }

Returns
String
The path to the Application Data directory for the all users.
Exceptions
EnvironmentPermission
Controls access to system and user environment variables. Associated enumeration: Unrestricted.
DirectoryNotFoundException
The path is empty, usually because the operating system does not support the directory.

Examples
This example displays the path to the Application Data directory for the all users in a MessageBox.

Remarks
The SpecialDirectories object contains paths to commonly referenced directories.
SpecialDirectories.CurrentUserApplicationData
I n this Article
Gets a path name pointing to the Application Data directory for the current user.
public static string CurrentUserApplicationData { get; }

Returns
String
The path to the Application Data directory for the current user.
Exceptions
DirectoryNotFoundException
The path is empty, usually because the operating system does not support the directory.

Examples
This example displays the path to the Application Data directory for the current user in a MessageBox.

Remarks
The SpecialDirectories object contains paths to commonly referenced directories.
SpecialDirectories.Desktop
I n this Article
Gets a path name pointing to the Desktop directory.
public static string Desktop { get; }

Returns
String
The path to the Desktop directory.
Exceptions
DirectoryNotFoundException
The path is empty, usually because the operating system does not support the directory.

Examples
This example displays the path for the Desktop directory in a MessageBox.

Remarks
The SpecialDirectories object contains paths to commonly referenced directories.
SpecialDirectories.MyDocuments
I n this Article
Gets a path name pointing to the My Documents directory.
public static string MyDocuments { get; }

Returns
String
The path to the My Documents directory.
Exceptions
DirectoryNotFoundException
The path is empty, usually because the operating system does not support the directory.

Examples
This example displays the path for the My Documents directory in a MessageBox.

Remarks
The SpecialDirectories object contains paths to commonly referenced directories.
SpecialDirectories.MyMusic
I n this Article
Gets a path name pointing to the My Music directory.
public static string MyMusic { get; }

Returns
String
The path to the My Music directory.
Exceptions
DirectoryNotFoundException
The path is empty, usually because the operating system does not support the directory.

Examples
This example displays the path for the My Music directory in a MessageBox.

Remarks
The SpecialDirectories object contains paths to commonly referenced directories.
SpecialDirectories.MyPictures
I n this Article
Gets a path name pointing to the My Pictures directory.
public static string MyPictures { get; }

Returns
String
The path to the My Pictures directory.
Exceptions
DirectoryNotFoundException
The path is empty, usually because the operating system does not support the directory.

Examples
This example displays the path for the MyPictures directory in a MessageBox.

Remarks
The SpecialDirectories object contains paths to commonly referenced directories.
SpecialDirectories.ProgramFiles
I n this Article
Gets a path pointing to the Program Files directory.
public static string ProgramFiles { get; }

Returns
String
The path to the Program Files directory.
Exceptions
DirectoryNotFoundException
The path is empty, usually because the operating system does not support the directory.

Examples
This example displays the path for the Program Files directory in a MessageBox.

Remarks
The SpecialDirectories object contains paths to commonly referenced directories. The Program Files directory
contains the computer's program files.
SpecialDirectories.Programs
I n this Article
Gets a path name pointing to the Programs directory.
public static string Programs { get; }

Returns
String
The path to the Programs directory.
Exceptions
DirectoryNotFoundException
The path is empty, usually because the operating system does not support the directory.

Examples
This example displays the path for the Programs directory in a MessageBox.

Remarks
The SpecialDirectories object contains paths to commonly referenced directories. The Programs directory contains
the user's program groups.
SpecialDirectories
I n this Article
Returns an instance of the SpecialDirectories class.
public SpecialDirectories ();
SpecialDirectories.Temp
I n this Article
Gets a path name pointing to the Temp directory.
public static string Temp { get; }

Returns
String
The path to the Temp directory.
Exceptions
DirectoryNotFoundException
The path is empty, usually because the operating system does not support the directory.

Examples
This example displays the path for the Temp directory in a MessageBox.

Remarks
The SpecialDirectories object contains paths to commonly referenced directories.
TextFieldParser Class
Provides methods and properties for parsing structured text files.

D eclaration
public class TextFieldParser : IDisposable

I nheritance H ierarchy
Object

Remarks
The TextFieldParser object provides methods and properties for parsing structured text files. Parsing a text file with
the TextFieldParser is similar to iterating over a text file, while the ReadFields method to extract fields of text is
similar to splitting the strings.
The TextFieldParser can parse two types of files: delimited or fixed-width. Some properties, such as Delimiters and
HasFieldsEnclosedInQuotes are meaningful only when working with delimited files, while the FieldWidths property
is meaningful only when working with fixed-width files.
The following table lists examples of tasks involving the Microsoft.VisualBasic.FileIO.TextFieldParser object.

TO S EE

Read from a delimited text file How to: Read From Comma-Delimited Text Files

Read from a fixed-width text file How to: Read From Fixed-width Text Files

Read from a text file with multiple formats How to: Read From Text Files with Multiple Formats

Constructors
TextFieldParser(Stream)

Initializes a new instance of the TextFieldParser class.


D eclaration
public TextFieldParser (System.IO.Stream stream);

Parameters
stream Stream
Stream. The stream to be parsed.

TextFieldParser(TextReader)

Initializes a new instance of the TextFieldParser class.


D eclaration
public TextFieldParser (System.IO.TextReader reader);
Parameters
reader TextReader
TextReader. The TextReader stream to be parsed.

TextFieldParser(String)

Initializes a new instance of the TextFieldParser class.


D eclaration
public TextFieldParser (string path);

Parameters
path String
String . The complete path of the file to be parsed.

TextFieldParser(Stream, Encoding)

Initializes a new instance of the TextFieldParser class.


D eclaration
public TextFieldParser (System.IO.Stream stream, System.Text.Encoding defaultEncoding);

Parameters
stream Stream
Stream. The stream to be parsed.

defaultEncoding Encoding
Encoding. The character encoding to use if encoding is not determined from file. Default is UTF8.

TextFieldParser(String, Encoding)

Initializes a new instance of the TextFieldParser class.


D eclaration
public TextFieldParser (string path, System.Text.Encoding defaultEncoding);

Parameters
path String
String . The complete path of the file to be parsed.

defaultEncoding Encoding
Encoding. The character encoding to use if encoding is not determined from file. Default is UTF8.

TextFieldParser(Stream, Encoding, Boolean)


Initializes a new instance of the TextFieldParser class.
D eclaration
public TextFieldParser (System.IO.Stream stream, System.Text.Encoding defaultEncoding, bool
detectEncoding);

Parameters
stream Stream
Stream. The stream to be parsed.

defaultEncoding Encoding
Encoding. The character encoding to use if encoding is not determined from file. Default is UTF8.

detectEncoding Boolean
Boolean . Indicates whether to look for byte order marks at the beginning of the file. Default is True .

TextFieldParser(String, Encoding, Boolean)

Initializes a new instance of the TextFieldParser class.


D eclaration
public TextFieldParser (string path, System.Text.Encoding defaultEncoding, bool detectEncoding);

Parameters
path String
String . The complete path of the file to be parsed.

defaultEncoding Encoding
Encoding. The character encoding to use if encoding is not determined from file. Default is UTF8.

detectEncoding Boolean
Boolean . Indicates whether to look for byte order marks at the beginning of the file. Default is True .

TextFieldParser(Stream, Encoding, Boolean, Boolean)

Initializes a new instance of the TextFieldParser class.


D eclaration
public TextFieldParser (System.IO.Stream stream, System.Text.Encoding defaultEncoding, bool
detectEncoding, bool leaveOpen);

Parameters
stream Stream
Stream. The stream to be parsed.

defaultEncoding Encoding
Encoding. The character encoding to use if encoding is not determined from file. Default is UTF8.

detectEncoding Boolean
Boolean . Indicates whether to look for byte order marks at the beginning of the file. Default is True .

leaveOpen Boolean
Boolean . Indicates whether to leave stream open when the TextFieldParser object is closed. Default is False .

Properties
CommentTokens

Defines comment tokens. A comment token is a string that, when placed at the beginning of a line, indicates that
the line is a comment and should be ignored by the parser.
D eclaration
public string[] CommentTokens { get; set; }

P roperty Value
String[]
A string array that contains all of the comment tokens for the TextFieldParser object.

Delimiters

Defines the delimiters for a text file.


D eclaration
public string[] Delimiters { get; set; }

P roperty Value
String[]
A string array that contains all of the field delimiters for the TextFieldParser object.

EndOfData

Returns True if there are no non-blank, non-comment lines between the current cursor position and the end of
the file.
D eclaration
public bool EndOfData { get; }

P roperty Value
Boolean
True if there is no more data to read; otherwise, False .

ErrorLine

Returns the line that caused the most recent MalformedLineException exception.
D eclaration
D eclaration
public string ErrorLine { get; }

P roperty Value
String
The line that caused the most recent MalformedLineException exception.

ErrorLineNumber

Returns the number of the line that caused the most recent MalformedLineException exception.
D eclaration
public long ErrorLineNumber { get; }

P roperty Value
Int64
The number of the line that caused the most recent MalformedLineException exception.

FieldWidths

Denotes the width of each column in the text file being parsed.
D eclaration
public int[] FieldWidths { get; set; }

P roperty Value
Int32[]
An integer array that contains the width of each column in the text file that is being parsed.

HasFieldsEnclosedInQuotes

Denotes whether fields are enclosed in quotation marks when a delimited file is being parsed.
D eclaration
public bool HasFieldsEnclosedInQuotes { get; set; }

P roperty Value
Boolean
True if fields are enclosed in quotation marks; otherwise, False .

LineNumber

Returns the current line number, or returns -1 if no more characters are available in the stream.
D eclaration
public long LineNumber { get; }

P roperty Value
Int64
The current line number.

TextFieldType

Indicates whether the file to be parsed is delimited or fixed-width.


D eclaration
public Microsoft.VisualBasic.FileIO.FieldType TextFieldType { get; set; }

P roperty Value
FieldType
A TextFieldType value that indicates whether the file to be parsed is delimited or fixed-width.

TrimWhiteSpace

Indicates whether leading and trailing white space should be trimmed from field values.
D eclaration
public bool TrimWhiteSpace { get; set; }

P roperty Value
Boolean
True if leading and trailing white space should be trimmed from field values; otherwise, False .

Methods
Close()

Closes the current TextFieldParser object.


D eclaration
public void Close ();

Dispose()

Releases resources used by the TextFieldParser object.


D eclaration
public void Dispose ();
Dispose(Boolean)

Releases resources used by the TextFieldParser object.


D eclaration
protected virtual void Dispose (bool disposing);

Parameters
disposing Boolean
Boolean. True releases both managed and unmanaged resources; False releases only unmanaged resources.

Finalize()

Allows the TextFieldParser object to attempt to free resources and perform other cleanup operations before it is
reclaimed by garbage collection.
D eclaration
~TextFieldParser ();

PeekChars(Int32)

Reads the specified number of characters without advancing the cursor.


D eclaration
public string PeekChars (int numberOfChars);

Parameters
numberOfChars Int32
Int32 . Number of characters to read. Required.

Returns
String
A string that contains the specified number of characters read.

ReadFields()

Reads all fields on the current line, returns them as an array of strings, and advances the cursor to the next line
containing data.
D eclaration
public string[] ReadFields ();

Returns
String[]
An array of strings that contains field values for the current line.
ReadLine()

Returns the current line as a string and advances the cursor to the next line.
D eclaration
public string ReadLine ();

Returns
String
The current line from the file or stream.

ReadToEnd()

Reads the remainder of the text file and returns it as a string.


D eclaration
public string ReadToEnd ();

Returns
String
The remaining text from the file or stream.

SetDelimiters(String[])

Sets the delimiters for the reader to the specified values, and sets the field type to Delimited .
D eclaration
public void SetDelimiters (string[] delimiters);

Parameters
delimiters String[]
Array of type String .

SetFieldWidths(Int32[])

Sets the delimiters for the reader to the specified values.


D eclaration
public void SetFieldWidths (int[] fieldWidths);

Parameters
fieldWidths Int32[]
Array of Integer .
TextFieldParser.Close
I n this Article
Closes the current TextFieldParser object.

public void Close ();

Examples
This example closes the TextFieldParser.FileReader .
TextFieldParser.CommentTokens
I n this Article
Defines comment tokens. A comment token is a string that, when placed at the beginning of a line, indicates that the
line is a comment and should be ignored by the parser.

public string[] CommentTokens { get; set; }

Returns
String[]
A string array that contains all of the comment tokens for the TextFieldParser object.
Exceptions
ArgumentException
A comment token includes white space.

Examples
This example specifies that for the TextFieldParser , FileReader lines beginning with a single quotation mark (')
should be ignored.

Remarks
This is an advanced member; it does not show in IntelliSense unless you click the All tab.
Zero-length comment tokens are ignored.
TextFieldParser.Delimiters
I n this Article
Defines the delimiters for a text file.
public string[] Delimiters { get; set; }

Returns
String[]
A string array that contains all of the field delimiters for the TextFieldParser object.
Exceptions
ArgumentException
A delimiter value is set to a newline character, an empty string, or Nothing .

Examples
This example specifies that the delimiter for the TextFieldParser object, FileReader , is a comma (,).

Remarks
This property is meaningful only if the TextFieldType property is set to FieldType.Delimited .
Defining the delimiters for a text file can also be accomplished with the SetDelimiters method.
The following table lists an example of a task involving the Delimiters property.

TO S EE

Read from a delimited text file How to: Read From Comma-Delimited Text Files
TextFieldParser.Dispose
I n this Article

Overloads
Dispose()
Releases resources used by the TextFieldParser object.

Dispose(​Boolean)
Releases resources used by the TextFieldParser object.

Dispose()
Releases resources used by the TextFieldParser object.
public void Dispose ();

Dispose(Boolean)
Releases resources used by the TextFieldParser object.
protected virtual void Dispose (bool disposing);

Parameters
disposing Boolean
Boolean. True releases both managed and unmanaged resources; False releases only unmanaged resources.
TextFieldParser.EndOfData
I n this Article
Returns True if there are no non-blank, non-comment lines between the current cursor position and the end of the file.

public bool EndOfData { get; }

Returns
Boolean
True if there is no more data to read; otherwise, False .

Examples
This example uses the EndofData property to loop through all the fields in the file with the TextFieldReader ,
FileReader .

Remarks
This property can be used when reading from files to determine the end of the data being read.
The following table lists examples of tasks involving the EndOfData property.

TO S EE

Read from a delimited file How to: Read From Comma-Delimited Text Files

Read from a fixed-width file How to: Read From Fixed-width Text Files
TextFieldParser.ErrorLine
I n this Article
Returns the line that caused the most recent MalformedLineException exception.
public string ErrorLine { get; }

Returns
String
The line that caused the most recent MalformedLineException exception.

Examples
This example uses the ErrorLine property to display the line causing the current MalformedLineException exception.

Remarks
If no MalformedLineException exceptions have been thrown, an empty string is returned.
The ErrorLineNumber property can be used to display the number of the line that caused the exception.
The following table lists examples of tasks involving the ErrorLine property.

TO S EE

Read from a delimited file How to: Read From Comma-Delimited Text Files

Read from a fixed-width file How to: Read From Fixed-width Text Files
TextFieldParser.ErrorLineNumber
I n this Article
Returns the number of the line that caused the most recent MalformedLineException exception.
public long ErrorLineNumber { get; }

Returns
Int64
The number of the line that caused the most recent MalformedLineException exception.

Examples
This example uses the ErrorLineNumber property to display the location of the line causing the current
MalformedLineException exception.

Remarks
If no MalformedLineException exceptions have been thrown, -1 is returned.
The ErrorLine property can be used to display the number of the line that caused the exception. Blank lines and
comments are not ignored when determining the line number.
The following table lists examples of tasks involving the ErrorLineNumber property.

TO S EE

Read from a delimited file How to: Read From Comma-Delimited Text Files

Read from a fixed-width file How to: Read From Fixed-width Text Files
TextFieldParser.FieldWidths
I n this Article
Denotes the width of each column in the text file being parsed.
public int[] FieldWidths { get; set; }

Returns
Int32[]
An integer array that contains the width of each column in the text file that is being parsed.
Exceptions
ArgumentException
A width value in any location other than the last entry of the array is less than or equal to zero.

Examples
This example reads the file ParserText.txt , specifying the widths; the first column is 5 characters wide, the second is
10, the third is 11, and the fourth is of variable width

Remarks
This property is meaningful only if the TextFieldType property is set to FieldType.FixedWidth . If the last entry in the
array is less than or equal to zero, the field is assumed to be of variable width.
The SetFieldWidths method can also be used to set field widths.
The following table lists examples of tasks involving the FieldWidths property.

TO S EE

Read from a fixed-width text file How to: Read From Fixed-width Text Files
TextFieldParser.Finalize
I n this Article
Allows the TextFieldParser object to attempt to free resources and perform other cleanup operations before it is
reclaimed by garbage collection.

~TextFieldParser ();
TextFieldParser.HasFieldsEnclosedInQuotes
I n this Article
Denotes whether fields are enclosed in quotation marks when a delimited file is being parsed.
public bool HasFieldsEnclosedInQuotes { get; set; }

Returns
Boolean
True if fields are enclosed in quotation marks; otherwise, False .

Examples
This example sets the HasFieldsEnclosedInQuotes property to True for myReader .

Remarks
This is an advanced member; it does not show in IntelliSense unless you click the All tab.
If the property is True , the parser assumes that fields are enclosed in quotation marks (" ") and may contain line
endings.
If a field is enclosed in quotation marks, for example, abc, "field2a,field2b", field3 and this property is True ,
then all text enclosed in quotation marks will be returned as is; this example would return
abc|field2a,field2b|field3 . Setting this property to False would make this example return
abc|"field2a|field2b"|field3 .
TextFieldParser.LineNumber
I n this Article
Returns the current line number, or returns -1 if no more characters are available in the stream.
public long LineNumber { get; }

Returns
Int64
The current line number.

Examples
This example searches for the name "Jones" in the text file and reports what line(s) it occurs on.

Remarks
This is an advanced member; it does not show in IntelliSense unless you click the All tab.
Blank lines and comments are not ignored when determining the line number.
TextFieldParser.PeekChars
I n this Article
Reads the specified number of characters without advancing the cursor.
public string PeekChars (int numberOfChars);

Parameters
numberOfChars Int32
Int32 . Number of characters to read. Required.

Returns
String
A string that contains the specified number of characters read.
Exceptions
ArgumentException
numberOfChars is less than 0.

Examples
This example uses PeekChars to find the end of the data and stop parsing the file at that point.

Remarks
The numberOfChars value must be less than the total number of characters in the line. If it is not, the string returned by
PeekChars will be truncated to the length of the line.

Blank lines are ignored.


End-of-line characters are not returned.
The PeekChars method performs no parsing; an end-of- line character within a delimited field is interpreted as the
actual end of the line.
The following table lists examples of tasks involving the PeekChars method.

TO S EE

Determine the format of a field before parsing it How to: Read From Text Files with Multiple Formats
TextFieldParser.ReadFields
I n this Article
Reads all fields on the current line, returns them as an array of strings, and advances the cursor to the next line
containing data.

public string[] ReadFields ();

Returns
String[]
An array of strings that contains field values for the current line.
Exceptions
MalformedLineException
A field cannot be parsed by using the specified format.

Examples
This example uses the ReadFields method to read from the comma-delimited file ParserText.txt . The example
writes the fields to Testfile.txt .

Remarks
In order to allow users to parse text files in multiple formats, the ReadFields method examines the values of
TextFieldType , Delimiters , and FieldWidths , if they are specified, each time it is called. Users need to correctly
configure the TextFieldType and FieldWidths or Delimiters properties, as appropriate. If TextFieldType is set to
Delimited , and Delimiters is not set, or if TextFieldType is set to FixedWidth and FieldWidths , an exception is
thrown.
If ReadFields encounters blank lines, they are skipped and the next non-blank line is returned.
If the ReadFields method cannot parse the current line, it raises an exception and does not move to the next line. This
enables your application to attempt to parse the line again.
The following table lists examples of tasks involving the ReadFields method.

TO S EE

Read from a delimited file How to: Read From Comma-Delimited Text Files

Read from a fixed-width file How to: Read From Fixed-width Text Files
TextFieldParser.ReadLine
I n this Article
Returns the current line as a string and advances the cursor to the next line.
public string ReadLine ();

Returns
String
The current line from the file or stream.

Examples
This example reads through the file ParserText.txt and writes it to Testfile.txt .

If Testfile.txt does not exist, it is created by the WriteAllText method.


This example writes the fields as a single string; to have each line display on its own line in the destination file, a
VbCrLf character should be appended at the end of each line.

Remarks
The ReadLine method performs no parsing; an end-of-line character within a delimited field is interpreted as the actual
end of the line.
Nothing is returned if the end of the file is reached.
TextFieldParser.ReadToEnd
I n this Article
Reads the remainder of the text file and returns it as a string.
public string ReadToEnd ();

Returns
String
The remaining text from the file or stream.

Examples
This example uses the ReadToEnd method to read the entire file ParserText.txt and write it to the file Testfile.txt .

If Testfile.txt does not exist, it is created by the WriteAllText method.

Remarks
This is an advanced member; it does not show in IntelliSense unless you click the All tab.
If there is nothing more to read because the end of the file has been reached, Nothing is returned.
The ReadToEnd method does not ignore blank lines and comments.
TextFieldParser.SetDelimiters
I n this Article
Sets the delimiters for the reader to the specified values, and sets the field type to Delimited .

public void SetDelimiters (string[] delimiters);

Parameters
delimiters String[]
Array of type String .
Exceptions
ArgumentException
A delimiter is zero-length.

Examples
This example opens a text field parser and defines the delimiter as vbTab .
Replace the path C:\logs est.log with the path and name of the file you wish to parse.

Remarks
The existing contents of the Delimiters property are cleared when this method is set.
This method provides a way to set delimiters without creating an array.
The following table lists an example of a task involving the SetDelimiters method.

TO S EE

Parse a text file Parsing Text Files with the TextFieldParser Object
TextFieldParser.SetFieldWidths
I n this Article
Sets the delimiters for the reader to the specified values.
public void SetFieldWidths (int[] fieldWidths);

Parameters
fieldWidths Int32[]
Array of Integer .

Examples
This example opens a text-field parser and defines the field width as 5 .
Replace the path C:\logs est.log with the path and name of the file you wish to parse.
The following example opens a text-field parser and defines the field widths as 5 , 10 , and variable.
Replace the path C:\logs est.log with the path and name of the file you wish to parse.

Remarks
The existing contents of the Delimiters property are cleared when this is set.
This method provides a way to set delimiters without creating an array.
The following table lists example of tasks involving the SetFieldWidths method.

TO S EE

Parse a text file. Parsing Text Files with the TextFieldParser Object
TextFieldParser
I n this Article

Overloads
Text​Field​Parser(​Stream)
Initializes a new instance of the TextFieldParser class.

Text​Field​Parser(​Text​Reader)
Initializes a new instance of the TextFieldParser class.

Text​Field​Parser(​String)
Initializes a new instance of the TextFieldParser class.

Text​Field​Parser(​Stream, ​Encoding)
Initializes a new instance of the TextFieldParser class.

Text​Field​Parser(​String, ​Encoding)
Initializes a new instance of the TextFieldParser class.

Text​Field​Parser(​Stream, ​Encoding, ​Boolean)


Initializes a new instance of the TextFieldParser class.

Text​Field​Parser(​String, ​Encoding, ​Boolean)


Initializes a new instance of the TextFieldParser class.

Text​Field​Parser(​Stream, ​Encoding, ​Boolean, ​Boolean)


Initializes a new instance of the TextFieldParser class.

TextFieldParser(Stream)
Initializes a new instance of the TextFieldParser class.

public TextFieldParser (System.IO.Stream stream);

Parameters
stream Stream
Stream. The stream to be parsed.
Exceptions
ArgumentNullException
stream is Nothing .
ArgumentException
stream cannot be read from.
Remarks
Creates a new TextFieldParser object to parse the file or stream that is represented by the stream parameter.

TextFieldParser(TextReader)
Initializes a new instance of the TextFieldParser class.

public TextFieldParser (System.IO.TextReader reader);

Parameters
reader TextReader
TextReader. The TextReader stream to be parsed.
Exceptions
ArgumentNullException
reader is Nothing .
Remarks
Creates a new TextFieldParser object to parse the file or stream that is represented by the reader parameter.

TextFieldParser(String)
Initializes a new instance of the TextFieldParser class.

public TextFieldParser (string path);

Parameters
path String
String . The complete path of the file to be parsed.

Exceptions
ArgumentNullException
path is an empty string.
Remarks
Creates a new TextFieldParser object to parse the file specified by the path parameter.

TextFieldParser(Stream, Encoding)
Initializes a new instance of the TextFieldParser class.

public TextFieldParser (System.IO.Stream stream, System.Text.Encoding defaultEncoding);

Parameters
stream Stream
Stream. The stream to be parsed.
defaultEncoding Encoding
Encoding. The character encoding to use if encoding is not determined from file. Default is UTF8.
Exceptions
ArgumentNullException
stream or defaultEncoding is Nothing .

ArgumentException
stream cannot be read from.
Remarks
Creates a new TextFieldParser object to parse the file or stream that is represented by the stream parameter.
Cautio n

When you compile a set of characters with a particular cultural setting and retrieve those same characters with a
different cultural setting, the characters might not be interpretable and could cause an exception to be thrown.

TextFieldParser(String, Encoding)
Initializes a new instance of the TextFieldParser class.

public TextFieldParser (string path, System.Text.Encoding defaultEncoding);

Parameters
path String
String . The complete path of the file to be parsed.

defaultEncoding Encoding
Encoding. The character encoding to use if encoding is not determined from file. Default is UTF8.
Exceptions
ArgumentNullException
path is an empty string or defaultEncoding is Nothing .
Remarks
Creates a new TextFieldParser object to parse the file specified by the path parameter.
Cautio n

When you compile a set of characters with a particular cultural setting and retrieve those same characters with a
different cultural setting, the characters might not be interpretable and could cause an exception to be thrown.

TextFieldParser(Stream, Encoding, Boolean)


Initializes a new instance of the TextFieldParser class.

public TextFieldParser (System.IO.Stream stream, System.Text.Encoding defaultEncoding, bool


detectEncoding);

Parameters
stream Stream
Stream. The stream to be parsed.
defaultEncoding Encoding
Encoding. The character encoding to use if encoding is not determined from file. Default is UTF8.
detectEncoding Boolean
Boolean . Indicates whether to look for byte order marks at the beginning of the file. Default is True .

Exceptions
ArgumentNullException
stream or defaultEncoding is Nothing .
ArgumentException
stream cannot be read from.
Remarks
Creates a new TextFieldParser object to parse the file or stream that is represented by the stream parameter.

If the detectEncoding parameter is True , this constructor attempts to detect the encoding by looking at the first three
bytes of the file or stream. It automatically recognizes UTF-8, little-endian Unicode, and big-endian Unicode text if the
file starts with the appropriate byte-order marks. Otherwise, the encoding specified by defaultEncoding is used.
Cautio n

When you compile a set of characters with a particular cultural setting and retrieve those same characters with a
different cultural setting, the characters might not be interpretable and could cause an exception to be thrown.

TextFieldParser(String, Encoding, Boolean)


Initializes a new instance of the TextFieldParser class.

public TextFieldParser (string path, System.Text.Encoding defaultEncoding, bool detectEncoding);

Parameters
path String
String . The complete path of the file to be parsed.

defaultEncoding Encoding
Encoding. The character encoding to use if encoding is not determined from file. Default is UTF8.
detectEncoding Boolean
Boolean . Indicates whether to look for byte order marks at the beginning of the file. Default is True .

Exceptions
ArgumentNullException
path is an empty string or defaultEncoding is Nothing .
Remarks
Creates a new TextFieldParser object to parse the file specified by the path parameter.
If the detectEncoding parameter is True , this constructor attempts to detect the encoding by looking at the first three
bytes of the file or stream. It automatically recognizes UTF-8, little-endian Unicode, and big-endian Unicode text if the
file starts with the appropriate byte-order marks. Otherwise, the encoding specified by defaultEncoding is used.
Cautio n

When you compile a set of characters with a particular cultural setting and retrieve those same characters with a
different cultural setting, the characters might not be interpretable and could cause an exception to be thrown.

TextFieldParser(Stream, Encoding, Boolean, Boolean)


Initializes a new instance of the TextFieldParser class.

public TextFieldParser (System.IO.Stream stream, System.Text.Encoding defaultEncoding, bool


detectEncoding, bool leaveOpen);

Parameters
stream Stream
Stream. The stream to be parsed.
defaultEncoding Encoding
Encoding. The character encoding to use if encoding is not determined from file. Default is UTF8.
detectEncoding Boolean
Boolean . Indicates whether to look for byte order marks at the beginning of the file. Default is True .

leaveOpen Boolean
Boolean . Indicates whether to leave stream open when the TextFieldParser object is closed. Default is False .

Exceptions
ArgumentNullException
stream or defaultEncoding is Nothing .

ArgumentException
stream cannot be read from.
Remarks
Creates a new TextFieldParser object to parse the file or stream that is represented by the stream parameter.

If the detectEncoding parameter is True , this constructor attempts to detect the encoding by looking at the first three
bytes of the file or stream. It automatically recognizes UTF-8, little-endian Unicode, and big-endian Unicode text if the
file starts with the appropriate byte-order marks. Otherwise, the encoding specified by defaultEncoding is used.
Cautio n

When you compile a set of characters with a particular cultural setting and retrieve those same characters with a
different cultural setting, the characters might not be interpretable and could cause an exception to be thrown.
TextFieldParser.TextFieldType
I n this Article
Indicates whether the file to be parsed is delimited or fixed-width.
public Microsoft.VisualBasic.FileIO.FieldType TextFieldType { get; set; }

Returns
FieldType
A TextFieldType value that indicates whether the file to be parsed is delimited or fixed-width.

Examples
This example creates a TextFieldParser , FileReader , and specifies that it is delimited.

This example creates a TextFieldParser , FileReader , and specifies that it is fixed-width.

Remarks
The default value of this property is delimited.
The following table lists examples of tasks involving the TextFieldType property.

TO S EE

Read from a delimited text file How to: Read From Comma-Delimited Text Files

Read from a fixed-width text file How to: Read From Fixed-width Text Files

Read from a text file with multiple formats How to: Read From Text Files with Multiple Formats
TextFieldParser.TrimWhiteSpace
I n this Article
Indicates whether leading and trailing white space should be trimmed from field values.
public bool TrimWhiteSpace { get; set; }

Returns
Boolean
True if leading and trailing white space should be trimmed from field values; otherwise, False .

Examples
This example creates a TextFieldParser , FileReader , and sets the TrimWhiteSpace property to True .

Remarks
The default value for this property is True .
UICancelOption Enum
Specifies whether an exception is thrown if the user clicks Cancel during an operation.

D eclaration
public enum UICancelOption

I nheritance H ierarchy
Object
ValueType
Enum

Remarks
This enumeration determines whether an OperationCanceledException is thrown when a user clicks Cancel during an
operation. In either case, the operation is canceled.

Fields
DoNothing Do nothing when the user clicks Cancel.

ThrowException Throw an exception when the user clicks Cancel.


UICancelOption.DoNothing
I n this Article
Do nothing when the user clicks Cancel.
DoNothing

Returns
UICancelOption
UICancelOption.ThrowException
I n this Article
Throw an exception when the user clicks Cancel.
ThrowException

Returns
UICancelOption
UIOption Enum
Specifies which dialog boxes to show when copying, deleting, or moving files or directories.

D eclaration
public enum UIOption

I nheritance H ierarchy
Object
ValueType
Enum

Remarks
This enumeration is used with CopyDirectory, CopyFile, DeleteDirectory, DeleteFile, MoveDirectory, and MoveFile
methods.

Fields
AllDialogs Show progress dialog box and any error dialog boxes.

OnlyErrorDialogs Only show error dialog boxes and hide progress dialog boxes. Default.
UIOption.AllDialogs
I n this Article
Show progress dialog box and any error dialog boxes.
AllDialogs

Returns
UIOption
UIOption.OnlyErrorDialogs
I n this Article
Only show error dialog boxes and hide progress dialog boxes. Default.
OnlyErrorDialogs

Returns
UIOption

You might also like