Appendix U

Filesystem Classes

A Visual Basic application can take three basic approaches to filesystem manipulation: Visual Basic methods, System.IO Framework classes, and the My.Computer.FileSystem namespace. This appendix summarizes the properties, methods, and events provided by these approaches. For more information on filesystem objects, see Chapter 30, “Filesystem Objects.”

VISUAL BASIC METHODS

The following table summarizes the Visual Basic methods for working with files. They let a program create, open, read, write, and learn about files.

METHOD PURPOSE
EOF Returns True if the file is at the end of file.
FileClose Closes an open file.
FileGet Reads data from a file opened in Random and Binary mode into a variable.
FileGetObject Reads data as an object from a file opened in Random and Binary mode into a variable.
FileOpen Opens a file for reading or writing. Parameters indicate the mode (Append, Binary, Input, Output, or Random), access type (Read, Write, or ReadWrite), and sharing (Shared, LockRead, LockWrite, or LockReadWrite).
FilePut Writes data from a variable into a file opened for Random or Binary access.
FilePutObject Writes an object from a variable into a file opened for Random or Binary access.
FreeFile Returns a file number that is not currently associated with any file in this application. You should use FreeFile to get file numbers rather than use arbitrary numbers such as 1.
Input Reads data written into a file by the Write method back into a variable.
InputString Reads a specific number of characters from the file.
LineInput Returns the next line of text from the file.
Loc Returns the current position within the file.
LOF Returns the file’s length in bytes.
Print Prints values into the file. Multiple values separated by commas are aligned at tab boundaries.
PrintLine Prints values followed by a new line into the file. Multiple values separated by commas are aligned at tab boundaries.
Seek Moves to the indicated position within the file.
Write Writes values into the file, delimited appropriately so that they can later be read by the Input method.
WriteLine Writes values followed by a new line into the file, delimited appropriately so that they can later be read by the Input method.

The following table describes Visual Basic methods that manipulate directories and files. They let an application list, rename, move, copy, and delete files and directories.

METHOD PURPOSE
ChDir Changes the application’s current working directory.
ChDrive Changes the application’s current working drive.
CurDir Returns the application’s current working directory.
Dir Returns a file matching a directory path specification that may include wildcards, and matching certain file properties such as ReadOnly, Hidden, or Directory. The first call to Dir should include a path. Subsequent calls can omit the path to fetch the next matching file for the initial path. Dir returns filenames without the path and returns Nothing when no more files match.
FileCopy Copies a file to a new location.
FileDateTime Returns the date and time when the file was created or last modified.
FileLen Returns the length of a file in bytes.
GetAttr Returns a value indicating the file’s attributes. The value is a combination of the values vbNormal, vbReadOnly, vbHidden, vbSystem, vbDirectory, vbArchive, and vbAlias.
Kill Permanently deletes a file.
MkDir Creates a new directory.
Rename Renames a directory or file.
RmDir Deletes an empty directory.
SetAttr Sets the file’s attributes. The value is a combination of the values vbNormal, vbReadOnly, vbHidden, vbSystem, vbDirectory, vbArchive, and vbAlias.

FRAMEWORK CLASSES

The System.IO namespace provides several classes for working with the filesystem. The following sections describe the properties, methods, and events provided by these classes.

Directory

The Directory class provides shared methods for working with directories. The following table summarizes its shared methods.

METHOD PURPOSE
CreateDirectory Creates all of the directories along a path.
Delete Deletes a directory and its contents. It can recursively delete all subdirectories.
Exists Returns True if the path points to an existing directory.
GetCreationTime Returns a directory’s creation date and time.
GetCreationTimeUtc Returns a directory’s creation date and time in Coordinated Universal Time (UTC).
GetCurrentDirectory Returns the application’s current working directory.
GetDirectories Returns an array of strings holding the fully qualified names of a directory’s subdirectories.
GetDirectoryRoot Returns the directory root for a path, which need not exist (for example, C:).
GetFiles Returns an array of strings holding the fully qualified names of a directory’s files.
GetFileSystemEntries Returns an array of strings holding the fully qualified names of a directory’s files and subdirectories.
GetLastAccessTime Returns a directory’s last access date and time.
GetLastAccessTimeUtc Returns a directory’s last access date and time in UTC.
GetLastWriteTime Returns the date and time when a directory was last modified.
GetLastWriteTimeUtc Returns the date and time when a directory was last modified in UTC.
GetLogicalDrives Returns an array of strings listing the system’s logical drives as in A:. The list includes drives that are attached. For example, it lists an empty floppy drive and a connected flash disk but doesn’t list a flash disk after you disconnect it.
GetParent Returns a DirectoryInfo object representing a directory’s parent directory.
Move Moves a directory and its contents to a new location on the same disk volume.
SetCreationTime Sets a directory’s creation date and time.
SetCreationTimeUtc Sets a directory’s creation date and time in UTC.
SetCurrentDirectory Sets the application’s current working directory.
SetLastAccessTime Sets a directory’s last access date and time.
SetLastAccessTimeUtc Sets a directory’s last access date and time in UTC.
SetLastWriteTime Sets a directory’s last write date and time.
SetLastWriteTimeUtc Sets a directory’s last write date and time in UTC.

File

The File class provides shared methods for working with files. The following table summarizes its most useful shared methods.

METHOD PURPOSE
AppendAllText Adds text to the end of a file, creating it if it doesn’t exist, and then closes the file.
AppendText Opens a file for appending UTF-8 encoded text and returns a StreamWriter attached to it. (For more information on UTF-8, see http://en.wikipedia.org/wiki/UTF-8.)
Copy Copies a file.
Create Creates a new file and returns a FileStream attached to it.
CreateText Creates or opens a file for writing UTF-8 encoded text and returns a StreamWriter attached to it.
Delete Permanently deletes a file.
Exists Returns True if the specified file exists.
GetAttributes Gets a file’s attributes. This is a combination of flags defined by the FileAttributes enumeration, which defines the values Archive, Compressed, Device, Directory, Encrypted, Hidden, Normal, NotContextIndexed, Offline, ReadOnly, ReparsePoint, SparseFile, System, and Temporary.
GetCreationTime Returns a file’s creation date and time.
GetCreationTimeUtc Returns a file’s creation date and time in UTC.
GetLastAccessTime Returns a file’s last access date and time.
GetLastAccessTimeUtc Returns a file’s last access date and time in UTC.
GetLastWriteTime Returns a file’s last write date and time.
GetLastWriteTimeUtc Returns a file’s last write date and time in UTC.
Move Moves a file to a new location.
Open Opens a file and returns a FileStream attached to it. Parameters let you specify the mode (Append, Create, CreateNew, Open, OpenOrCreate, or Truncate), access (Read, Write, or ReadWrite), and sharing (Read, Write, ReadWrite, or None) settings.
OpenRead Opens a file for reading and returns a FileStream attached to it.
OpenText Opens a UTF-8 encoded text file for reading and returns a StreamReader attached to it.
OpenWrite Opens a file for writing and returns a FileStream attached to it.
ReadAllBytes Returns a file’s contents into an array of bytes.
ReadAllLines Returns a file’s lines into an array of strings.
ReadAllText Returns a file’s contents into a string.
Replace This method takes three file paths as parameters representing a source file, a destination file, and a backup file. If the backup file exists, the method permanently deletes it. It then moves the destination file to the backup file, and moves the source file to the destination file. This method throws an exception if either the source file or the destination file doesn’t exist.
SetAttributes Sets a file’s attributes. This is a combination of flags defined by the FileAttributes enumeration, which defines the values Archive, Compressed, Device, Directory, Encrypted, Hidden, Normal, NotContextIndexed, Offline, ReadOnly, ReparsePoint, SparseFile, System, and Temporary.
SetCreationTime Sets a file’s creation date and time.
SetCreationTimeUtc Sets a file’s creation date and time in UTC.
SetLastAccessTime Sets a file’s last access date and time.
SetLastAccessTimeUtc Sets a file’s last access date and time in UTC.
SetLastWriteTime Sets a file’s last write date and time.
SetLastWriteTimeUtc Sets a file’s last write date and time in UTC.
WriteAllBytes Creates or overwrites a file, writes an array of bytes into it, and closes the file.
WriteAllLines Creates or overwrites a file, writes an array of strings into it, and closes the file.
WriteAllText Creates or overwrites a file, writes a string into it, and closes the file.

DriveInfo

A DriveInfo object represents one of the computer’s drives. The following table describes the properties provided by this class. The final column in the table indicates whether a drive must be ready for the property to work without throwing an exception. Use the IsReady property to see whether the drive is ready before using those properties.

PROPERTY PURPOSE MUST BE READY?
AvailableFreeSpace Returns the amount of free space available on the drive in bytes. This value takes quotas into account, so it may not match TotalFreeSpace. True
DriveFormat Returns the name of the filesystem type such as NTFS or FAT32. (For more information on NTFS and FAT filesystems, search the web. For example, the page http://www.ntfs.com/ntfs_vs_fat.htm compares the FAT, FAT32, and NTFS filesystems.) True
DriveType Returns a DriveType enumeration value indicating the drive type. This value can be CDRom, Fixed, Network, NoRootDirectory, Ram, Removable, or Unknown. False
IsReady Returns True if the drive is ready. Many DriveInfo properties are unavailable and raise exceptions if you try to access them while the drive is not ready. False
Name Return’s the drive’s name. This is the drive’s root name as in A: or C:. False
RootDirectory Returns a DirectoryInfo object representing the drive’s root directory. See the section “DirectoryInfo” later in this appendix for more information. False
TotalFreeSpace Returns the total amount of free space on the drive in bytes. True
TotalSize Returns the total amount of space on the drive in bytes. True
VolumeLabel Gets or sets the drive’s volume label. True

DirectoryInfo

A DirectoryInfo object represents a directory. The following table summarizes its most useful properties and methods.

PROPERTY OR METHOD PURPOSE
Attributes Gets or sets flags from the FileAttributes enumeration for the directory. These flags can include Archive, Compressed, Device, Directory, Encrypted, Hidden, Normal, NotContentIndexed, Offline, ReadOnly, ReparsePoint, SparseFile, System, and Temporary.
Create Creates the directory. You can create a DirectoryInfo object, passing its constructor the fully qualified name of a directory that doesn’t exist. You can then call the object’s Create method to create the directory.
CreateSubdirectory Creates a subdirectory within the directory and returns a DirectoryInfo object representing it. The subdirectory’s path must be relative to the DirectoryInfo object’s directory but can contain intermediate subdirectories. For example, the statement dir_info.CreateSubdirectory(“ToolsBin”) creates the Tools subdirectory and the Bin directory inside that.
CreationTime Gets or sets the directory’s creation time.
CreationTimeUtc Gets or sets the directory’s creation time in UTC.
Delete Deletes the directory if it is empty. A parameter lets you tell the object to delete its contents, too, if it isn’t empty.
Exists Returns True if the directory exists.
Extension Returns the extension part of the directory’s name. Normally, this is an empty string for directories.
FullName Returns the directory’s fully qualified path.
GetDirectories Returns an array of DirectoryInfo objects representing the directory’s subdirectories. An optional parameter gives a pattern to match. This method does not recursively search the subdirectories.
GetFiles Returns an array of FileInfo objects representing files inside the directory. An optional parameter gives a pattern to match. This method does not recursively search subdirectories.
GetFileSystemInfos Returns a strongly typed array of FileSystemInfo objects representing subdirectories and files inside the directory. The items in the array are DirectoryInfo and FileInfo objects, both of which inherit from FileSystemInfo. An optional parameter gives a pattern to match. This method does not recursively search subdirectories.
LastAccessTime Gets or sets the directory’s last access time.
LastAccessTimeUtc Gets or sets the directory’s last access time in UTC.
LastWriteTime Gets or sets the directory’s last write time.
LastWriteTimeUtc Gets or sets the directory’s last write time in UTC.
MoveTo Moves the directory and its contents to a new path.
Name Returns the directory’s name without the path information.
Parent Returns a DirectoryInfo object representing the directory’s parent. If the directory is its filesystem’s root (for example, C:), this returns Nothing.
Refresh Refreshes the DirectoryInfo object’s data. For example, if the directory has been accessed since the object was created, you must call Refresh to load the new LastAccessTime value.
Root Returns a DirectoryInfo object representing the root of the directory’s filesystem.
ToString Returns the directory’s fully qualified path and name.

FileInfo

A FileInfo object represents a file. The following table summarizes its most useful properties and methods.

PROPERTY OR METHOD PURPOSE
AppendText Returns a StreamWriter that appends text to the file.
Attributes Gets or sets flags from the FileAttributes enumeration for the file. These flags can include Archive, Compressed, Device, Directory, Encrypted, Hidden, Normal, NotContentIndexed, Offline, ReadOnly, ReparsePoint, SparseFile, System, and Temporary.
CopyTo Copies the file and returns a FileInfo object representing the new file. A parameter lets you indicate whether the copy should overwrite the destination file if it already exists. If the destination path is relative, it is relative to the application’s current directory, not to the FileInfo object’s directory.
Create Creates the file and returns a FileStream object attached to it. For example, you can create a FileInfo object passing its constructor the name of a file that doesn’t exist. Then you can call the Create method to create the file.
CreateText Creates the file and returns a StreamWriter attached to it. For example, you can create a FileInfo object passing its constructor the name of a file that doesn’t exist. Then you can call the CreateText method to create the file.
CreationTime Gets or sets the file’s creation time.
CreationTimeUtc Gets or sets the file’s creation time in UTC.
Delete Deletes the file.
Directory Returns a DirectoryInfo object representing the file’s directory.
DirectoryName Returns the name of the file’s directory.
Exists Returns True if the file exists.
Extension Returns the extension part of the file’s name including the period. For example, the extension for game.txt is .txt.
FullName Returns the file’s fully qualified path and name.
IsReadOnly Returns True if the file is marked read-only.
LastAccessTime Gets or sets the file’s last access time.
LastAccessTimeUtc Gets or sets the file’s last access time in UTC.
LastWriteTime Gets or sets the file’s last write time.
LastWriteTimeUtc Gets or sets the file’s last write time in UTC.
Length Returns the number of bytes in the file.
MoveTo Moves the file to a new location. If the destination uses a relative path, it is relative to the application’s current directory, not to the FileInfo object’s directory. When this method finishes, the FileInfo object is updated to refer to the file’s new location.
Name The file’s name without the path information.
Open Opens the file with different mode (Append, Create, CreateNew, Open, OpenOrCreate, or Truncate), access (Read, Write, or ReadWrite), and sharing (Read, Write, ReadWrite, or None) settings. This method returns a FileStream object attached to the file.
OpenRead Returns a read-only FileStream attached to the file.
OpenText Returns a StreamReader with UTF-8 encoding attached to the file for reading.
OpenWrite Returns a write-only FileStream attached to the file.
Refresh Refreshes the FileInfo object’s data. For example, if the file has been accessed since the object was created, you must call Refresh to load the new LastAccessTime value.
Replace Replaces a target file with this one, renaming the old target as a backup copy. If the backup file already exists, it is deleted and replaced with the target.
ToString Returns the file’s fully qualified name.

FileSystemWatcher

The FileSystemWatcher class lets an application watch for changes to a file or directory. The following table summarizes its most useful properties.

PROPERTY PURPOSE
EnableRaisingEvents Determines whether the component is enabled. Note that this property is False by default, so the watcher will not raise any events until you set it to True.
Filter Determines the files for which the watcher reports events. You cannot watch for multiple file types as in *.txt and *.dat. Instead, use multiple FileSystemWatchers. If you like, you can use AddHandler to make all of the FileSystemWatchers use the same event handlers.
IncludeSubdirectories Determines whether the object watches subdirectories within the main path.
InternalBufferSize Determines the size of the internal buffer. If the watcher is monitoring a very active directory, a small buffer may overflow.
NotifyFilter Determines the types of changes that the watcher reports. This is a combination of values defined by the NotifyFilters enumeration and can include the values Attributes, CreationTime, DirectoryName, FileName, LastAccess, LastWrite, Security, and Size.
Path Determines the path to watch.

The following table summarizes the FileSystemWatcher class’s two most useful methods.

METHOD PURPOSE
Dispose Releases resources used by the object.
WaitForChanged Synchronously waits for a change to the target file or directory.

The following table summarizes the class’s events.

NAME DESCRIPTION
Changed A file or subdirectory has changed.
Created A file or subdirectory was created.
Deleted A file or subdirectory was deleted.
Error The watcher’s internal buffer overflowed.
Renamed A file or subdirectory was renamed.

Path

The Path class provides shared properties and methods that you can use to manipulate paths. The following table summarizes its most useful public properties.

PROPERTY PURPOSE
AltDirectorySeparatorChar Returns the alternate character used to separate directory levels in a hierarchical path (typically /).
DirectorySeparatorChar Returns the character used to separate directory levels in a hierarchical path (typically , as in C:TestsBilling2010q2.dat).
InvalidPathChars Returns a character array that holds characters that are not allowed in a path string. Typically, this array will include characters such as ", <, >, and |, as well as nonprintable characters such as those with ASCII values between 0 and 31.
PathSeparator Returns the character used to separate path strings in environment variables (typically ;).
VolumeSeparatorChar Returns the character placed between a volume letter and the rest of the path (typically :, as in C:TestsBilling2010q2.dat).

The following table summarizes the Path class’s most useful methods.

METHOD PURPOSE
ChangeExtension Changes a path’s extension.
Combine Returns two path strings concatenated. This does not simplify the result as the My.Computer.FileSystem.CombinePath method does.
GetDirectoryName Returns a path’s directory.
GetExtension Returns a path’s extension.
GetFileName Returns a path’s filename and extension.
GetFileNameWithout Extension Returns a path’s filename without the extension.
GetFullPath Returns a path’s fully qualified value. This can be particularly useful for converting a partially relative path into an absolute path. For example, the statement Path.GetFullPath(“C:TestsOldTestsSoftware....NewCode”) returns C:TestsNewCode.
GetInvalidFileNameChars Returns a character array that holds characters that are not allowed in filenames.
GetPathRoot Returns a path’s root directory string. For example, the statement Path.GetPathRoot(“C:InvoicesUnpaidDeadbeats”) returns C:.
GetRandomFileName Returns a random filename.
GetTempFileName Creates a uniquely named, empty temporary file, and returns its fully qualified path. Your program can open that file for scratch space, do whatever it needs to do, close the file, and then delete it. A typical filename might be C:Documents and SettingsRodLocal SettingsTemp mp19D.tmp.
GetTempPath Returns the path to the system’s temporary folder. This is the path part of the filename returned by GetTempFileName.
HasExtension Returns True if a path includes an extension.
IsPathRooted Returns True if a path is an absolute path. This includes TempWherever and C:ClientsLitigation, but not TempWherever or ..Uncle.

MY.COMPUTER.FILESYSTEM

The My.Computer.FileSystem object provides tools for working with drives, directories, and files. The following table summarizes this object’s properties.

PROPERTY DESCRIPTION
CurrentDirectory Gets or sets the fully qualified path to the application’s current directory.
Drives Returns a read-only collection of DriveInfo objects describing the system’s drives. See Chapter 30, “Filesystem Objects,” for information about the DriveInfo class.
SpecialDirectories Returns a SpecialDirectoriesProxy object that has properties giving the locations of various special directories such as the system’s temporary directory and the user’s My Documents directory. See the section “My.Computer.FileSystem.SpecialDirectories” later in this appendix for more information.

The following list summarizes the My.Computer.FileSystem object’s methods:

METHOD PURPOSE
CombinePath Combines a base path with a relative path reference and returns a properly formatted fully qualified path.
CopyDirectory Copies a directory. Parameters indicate whether to overwrite existing files, whether to display a progress indicator, and what to do if the user presses Cancel during the operation.
CopyFile Copies a file. Parameters indicate whether to overwrite existing files, whether to display a progress indicator, and what to do if the user presses Cancel during the operation.
CreateDirectory Creates all of the directories along a path.
DeleteDirectory Deletes a directory. Parameters indicate whether to recursively delete subdirectories, prompt the user for confirmation, or move the directory into the Recycle Bin.
DeleteFile Deletes a file. Parameters indicate whether to prompt the user for confirmation, or move the file into the Recycle Bin, and what to do if the user presses Cancel while the deletion is in progress.
DirectoryExists Returns True if a specified directory exists.
FileExists Returns True if a specified file exists.
FindInFiles Returns a collection holding names of files that contain a search string.
GetDirectories Returns a string collection listing subdirectories of a given directory. Parameters tell whether to recursively search the subdirectories and wildcards to match.
GetDirectoryInfo Returns a DirectoryInfo object for a directory. See the section “DirectoryInfo” earlier in this appendix for more information.
GetDriveInfo Returns a DriveInfo object for a drive. See the section “DriveInfo” earlier in this appendix for more information.
GetFileInfo Returns a FileInfo object for a file. See the section “FileInfo” earlier in this appendix for more information.
GetFiles Returns a string collection holding the names of files within a directory. Parameters indicate whether the search should recursively search subdirectories and give wildcards to match.
GetParentPath Returns the fully qualified path of a path’s parent.
MoveDirectory Moves a directory. Parameters indicate whether to overwrite files that have the same name in the destination directory and whether to prompt the user when such a collision occurs.
MoveFile Moves a file. Parameters indicate whether to overwrite a file that has the same name as the file’s destination and whether to prompt the user when such a collision occurs.
OpenTextFieldParser Opens a TextFieldParser object attached to a delimited or fixed-field file (such as a log file). You can use the object to parse the file.
OpenTextFileReader Opens a StreamReader object attached to a file. You can use the object to read the file.
OpenTextFileWriter Opens a StreamReader object attached to a file. You can use the object to write into the file.
ReadAllBytes Reads all the bytes from a binary file into an array.
ReadAllText Reads all the text from a text file into a string.
RenameDirectory Renames a directory within its parent directory.
RenameFile Renames a file within its directory.
WriteAllBytes Writes an array of bytes into a binary file. A parameter tells whether to append the data or rewrite the file.
WriteAllText Writes a string into a text file. A parameter tells whether to append the string or rewrite the file.

MY.COMPUTER.FILESYSTEM.SPECIALDIRECTORIES

The My.Computer.FileSystem.SpecialDirectories property returns a SpecialDirectoriesProxy object that has properties giving the locations of various special directories (such as the system’s temporary directory and the user’s My Documents directory). The following table summarizes these special directory properties.

PROPERTY PURPOSE
AllUsersApplicationData The directory where applications should store settings for all users (typically, something like C:ProgramDataWindowsApplication1WindowsApplication11.0.0.0).
CurrentUserApplicationData The directory where applications should store settings for the current user (typically, something like C:UsersCrazyBobAppDataRoamingWindowsApplication1WindowsApplication11.0.0.0).
Desktop The current user’s desktop directory (typically, C:UsersCrazyBobDesktop).
MyDocuments The current user’s My Documents directory (typically, C:UsersCrazyBobDocuments).
MyMusic The current user’s My Music directory (typically, C:UsersCrazyBobMusic).
MyPictures The current user’s My Pictures directory (typically, C:UsersCrazyBobPictures).
ProgramFiles The Program Files directory (typically, C:Program Files).
Programs The current user’s Programs directory (typically, C:UsersCrazyBobAppDataRoamingMicrosoftWindowsStart MenuPrograms).
Temp The current user’s temporary directory (typically, C:UsersCrazyBobAppDataLocalTemp).
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.186.12