.NET Framework Classes


The System.IO namespace provides several classes for working with the file system. The Directory and File classes provide shared methods that you can use to manipulate the file system without creating instances of helper objects.

The DirectoryInfo and FileInfo classes let you work with specific relevant file system objects. For example, a FileInfo object represents a particular file and provides methods to create, rename, delete, and get information about that file.

The following sections describe these and the other classes that the Framework provides to help you work with the file system.

Directory

The Directory class provides shared methods for working with directories. These methods let you create, rename, move, and delete directories. They let you enumerate the files and subdirectories within a directory, and get and set directory information such as the directory’s creation and last access time.

The following table describes the Directory class’s shared methods.

Open table as spreadsheet

Method

Purpose

CreateDirectory

Creates a directory and any missing ancestors (parent, grandparent, and so on).

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 (the path 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 in UTC when a directory was last modified.

GetLogicalDrives

Returns an array of strings listing the system’s logical drives as in A:\. The list only 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.

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. These methods let you create, rename, move, and delete files. They also make working with file streams a bit easier.

The following table describes the File class’s most useful shared methods.

Open table as spreadsheet

Method

Purpose

AppendAll

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 class 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 class 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: 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, OpenOr?Create, 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 Stream?Reader 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: 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. Note that some of these properties are available only when the drive is ready, as indicated in the Must Be Ready column. If you try to access them when the drive is not ready, Visual Basic throws an exception. The program should check the IsReady property to determine whether the drive is ready before trying to use the AvailableFreeSpace, DriveFormat, TotalFreeSpace, or VolumeLabel properties.

Open table as spreadsheet

DriveInfo Property

Purpose

Must Be Ready

AvailableFreeSpace

Returns the amount of free space available on the drive in bytes.

True

DriveFormat

Returns the name of the file-system type such as NTFS (NT File System) or FAT32 (32-bit File Allocation Table). (For a comparison of these, see www.ntfs.com/ntfs_vs_fat.htm.)

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 chapter for more information on this class.

False

TotalFreeSpace

Returns the total amount of free space on the drive in bytes.

True

VolumeLabel

Gets or sets the drive’s volume label.

True

The DriveInfo class also has a public shared method GetDrives that returns an array of DriveInfo objects describing the system’s drives.

DirectoryInfo

A DirectoryInfo object represents a directory. You can use its properties and methods to create and delete directories and to move through a directory hierarchy.

The following table describes the most useful public properties and methods provided by the Directory?Info class.

Open table as spreadsheet

Property or Method

Purpose

Attributes

Gets or sets flags for the directory from the FileAttributes enumeration: 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, 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 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 directory’s last write time in UTC.

MoveTo

Moves the directory and its contents to a new path.

Name

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:\), then 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

AFileInfo object represents a file. You can use its properties and methods to create and delete directories and to move through a directory hierarchy.

The following table describes the most useful public properties and methods provided by the File?Info class.

Open table as spreadsheet

Property or Method

Purpose

AppendText

Returns a StreamWriter that appends text to the file.

Attributes

Gets or sets flags for the file from the FileAttributes enumeration: 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 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 various 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.

FileSystemInfo

The FileSystemInfo class is the parent class for the FileInfo and DirectoryInfo classes. It is a Must?Inherit class so you cannot create instances of it directly, but some routines return this class rather than the more specific child classes. For example, the DirectoryInfo class’s GetFileSystemInfos method returns an array of FileSystemInfo objects describing the files in the directory.

FileSystemWatcher

The FileSystemWatcher class keeps an eye on part of the file system and raises events to let your program know if something changes. For example, you could make a FileSystemWatcher monitor a work directory. For example, when a new file with a .job extension arrives, the watcher would raise an event and your application could process the file.

The FileSystemWatcher class’s constructor takes parameters that tell it which directory to watch and that give it a filter for selecting files to watch. For example, the filter might be “*.txt” to watch for changes to text files. The default filter is “*.*”, which catches changes to all files that have an extension. Set the filter to the empty string “” to catch changes to all files.

The following table describes the FileSystemWatcher class’s 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 FileSystemWatcher classes. If you like, you can use AddHandler to make all of the FileSystemWatcher classes 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 enumerration and can include the values Attributes, CreationTime, Directory?Name, FileName, LastAccess, LastWrite, Security, and Size.

Path

Determines the path to watch.

The FileSystemWatcher class provides only two really useful methods. First, Dispose releases resources used by the component. When you are finished using a watcher, call its Dispose method to allow garbage collection to reclaim its resources more efficiently.

Second, the WaitForChanged method waits for a change synchronously (with an optional timeout). When a change occurs, the method returns a WaitForChangedResult object, giving information about the change that occurred.

When the FileSystemWatcher detects a change asynchronously, it raises an event to let the program know what has happened. The following table describes 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.

The following simple example shows how to use a FileSystemWatcher to look for new files in a directory. The program uses the WithEvents keyword to declare a FileSystemWatcher object. When the program’s main form loads, the Form1_Load event handler allocates this object. Its constructor sets the object’s path to the program’s startup directory’s parent. It sets the object’s filter to “*.job” so that the object will watch for changes to files that end with a .job extension.

The event handler sets the watcher’s NotifyFilter to FileName, so it will raise its Created event if a new file name appears in the target directory. Unfortunately, the NotifyFilter values (Attributes, CreationTime, DirectoryName, FileName, LastAccess, LastWrite, Security, and Size) do not match up well with the events provided by the FileSystemWatcher, so you need to figure out which NotifyFilter values to set to raise different kinds of events.

The Form1_Load event handler finishes by setting the watcher’s EnableRaisingEvents property to True so the object starts watching.

When a .job file’s is created in the watcher’s target directory, the program’s fswJobFiles_Created executes. The program processes and then deletes the file. In this example, the program processes the file by displaying a message giving its fully qualified name. A more realistic example might read the file; parse fields, indicating the type of job this is; assign it to an employee for handling; and then e-mail it to that employee.

  Private WithEvents fswJobFiles As FileSystemWatcher Private Sub Form1_Load(ByVal sender As System.Object, _  ByVal e As System.EventArgs) Handles MyBase.Load     Dim watch_path As String = _         FileSystem.GetParentPath(Application.StartupPath)     fswJobFiles = New FileSystemWatcher(watch_path, "*.job")     fswJobFiles.NotifyFilter = NotifyFilters.FileName     fswJobFiles.EnableRaisingEvents = True End Sub Private Sub fswJobFiles_Created(ByVal sender As Object, _  ByVal e As System.IO.FileSystemEventArgs) Handles fswJobFiles.Created     ' Process the new file...     MessageBox.Show("Process new job: " & e.FullPath)     File.Delete(e.FullPath) End Sub 

Path

The Path class provides shared properties and methods that you can use to manipulate paths. Its methods return the path’s file name, extension, directory name, and so forth. Other methods provide values that do not relate to a specific path. For example, they can give you the system’s temporary directory path, or the name of a temporary file.

The following table describes the Path class’s 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 this is /.

DirectorySeparatorChar

Returns the character used to separate directory levels in a hierarchical path. Typically this is \ (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 includes 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 this is ;.

VolumeSeparatorChar

Returns the character placed between a volume letter and the rest of the path. Typically this is : (as in C:\Tests\ Billing\2005q2.dat).

The following table describes 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.

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 the string “C:\Tests\New\Code”.

GetInvalidFileNameChars

Returns an array listing characters that are invalid in file names.

GetInvalidPathChars

Returns an array listing characters that are invalid in file paths.

GetPathRoot

Returns a path’s root directory string. For example, the statement Path.GetPathRoot(“C:\Invoices\ Unpaid\Deadbeats”) returns the string “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 the path part of the file names 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