Framework Classes


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

FileSystem

The FileSystem class provides shared methods for working with the file system at a large scale. The following table describes its most useful properties and methods.

Open table as spreadsheet

Property or Method

Purpose

CombinePath

Combines a base path with a relative child path and returns the resulting path. For example, the statement FileSystem .CombinePath(“C:\Someplace\Lost”, “..\Else”) returns C:\Someplace\Else.

CopyDirectory

Copies a directory and its contents to a new location. A parameter indicates whether you want to overwrite existing files that have the same names.

CopyFile

Copies a file to a new location, possibly overwriting an existing file.

CreateDirectory

Creates a new directory.

DeleteDirectory

Deletes an existing directory. Parameters indicate whether the method should recursively delete the directory’s contents and whether the deleted files should be placed in the Recycle Bin or deleted permanently.

DeleteFile

Deletes a file. A parameter indicates whether the file should be placed in the Recycle Bin or deleted permanently.

DirectoryExists

Returns True if the specified directory exists.

FileExists

Returns True if the specified file exists.

FindInFiles

Returns a collection holding names of files that contain a search string.

GetDirectories

Returns a read-only collection of strings giving the subdirectories within a specific directory. Parameters indicate whether the method should recursively search the subdirectories and whether the routine should allow wildcards.

GetDirectoryInfo

Returns a DirectoryInfo object representing a directory. Note that the directory need not exist yet. For example, you can create a DirectoryInfo object and then use its Create method to create the directory.

GetDriveInfo

Returns a DriveInfo object representing a drive.

GetFileInfo

Returns a FileInfo object representing a file. Note that the file need not exist yet. For example, you can create a FileInfo object and then use its Create method to create the file.

GetFiles

Returns a read-only collection of strings giving the names of files within a specific directory. Parameters indicate whether the method should recursively search the subdirectories and whether the routine should allow wildcards.

GetName

Returns the name portion of a file path.

GetParentPath

Returns a directory’s parent directory path.

GetTempFileName

Creates a uniquely named empty file and returns its full path.

MoveDirectory

Moves a directory to a new parent directory. A parameter indicates whether you want to overwrite existing files with the same names.

MoveFile

Moves a file to a new directory. Parameters indicate whether the file should overwrite an existing file at the new location.

OpenTextFieldParser

Returns a TextFieldParser for a file. A TextFieldParser makes it easy to read fields from a delimited file or from a file with fixed-width field columns.

OpenTextFileReader

Returns a StreamReader attached to a file.

OpenTextFileWriter

Returns a StreamWriter attached to a file. A parameter indicates whether the StreamWriter should append to the file or create a new file.

ReadAllBytes

Returns a file’s contents as an array of bytes.

ReadAllText

Returns a file’s contents as a string.

RenameDirectory

Changes a directory’s name within its current parent directory.

RenameFile

Changes a file’s name within its current directory.

WriteAllBytes

Writes a byte array into a file. A parameter indicates whether the method should append the bytes to the file or create a new file.

WriteAllText

Writes a string into a file. A parameter indicates whether the method should append the string to the file or create a new file.

Directory

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

Open table as spreadsheet

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.

Open table as spreadsheet

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.

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 in an array of bytes.

ReadAllLines

Returns a file’s lines in an array of strings.

ReadAllText

Returns a file’s contents in 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. For example, imagine a program that writes a log file every time it runs. It could use this method to keep three versions of the log: the current log (the method’s source file), the most recent backup (the method’s destination file), and a second backup (the method’s backup file). This method throws an error if either the source or 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 replaces a file, writes an array of bytes into it, and closes the file.

WriteAllLines

Creates or replaces a file, writes an array of strings into it, and closes the file.

WriteAllText

Creates or replaces 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.

Open table as spreadsheet

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 file system type (such as NTFS or FAT32).

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.

Open table as spreadsheet

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, NotContent?Indexed, 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(“Tools\ Bin”) 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 file system’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 file system.

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.

Open table as spreadsheet

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 an existing 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. You can use this method to save backups of logs and other periodically updated files.

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.

Open table as spreadsheet

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 Notify?Filters 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.

Open table as spreadsheet

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.

Open table as spreadsheet

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 fol-lowing table summarizes its most useful public properties.

Open table as spreadsheet

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:\Tests\Billing\ 2005q2.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:\Tests\Billing\ 2005q2.dat).

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

Open table as spreadsheet

Method

Purpose

ChangeExtension

Changes a path’s extension.

Combine

Returns two path strings concatenated. This does not simplify the result as the FileSystem.CombinePath method does.

GetDirectoryName

Returns a path’s directory.

GetExtension

Returns a path’s extension.

GetFileName

Returns a path’s file name and extension.

GetFileNameWithoutExtension

Returns a path’s file name 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:\ Tests\OldTests\Software\..\..\New\Code”) returns C:\Tests\New\Code.

GetInvalidFileNameChars

Returns a character array that holds characters that are not allowed in a file names.

GetPathRoot

Returns a path’s root directory string. For example, the statement Path.GetPathRoot(“C:\Invoices\Unpaid\ Deadbeats”) returns C:\.

GetRandomFileName

Returns a random file name.

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 file name might be C:\Documents and Settings\Rod\Local Settings\Temp\tmp19D.tmp.

GetTempPath

Returns the path to the system’s temporary folder. This is the path part of the file name returned by GetTempFileName.

HasExtension

Returns True if a path includes an extension.

IsPathRooted

Returns True if a path is an absolute path. This includes \Temp\Wherever and C:\Clients\Litigation, but not Temp\Wherever or ..\Uncle.




Visual Basic 2005 with  .NET 3.0 Programmer's Reference
Visual Basic 2005 with .NET 3.0 Programmer's Reference
ISBN: 470137053
EAN: N/A
Year: 2007
Pages: 417

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net