Appendix S
Filesystem Classes

This appendix describes the .NET Framework’s filesystem classes. It also summarizes methods you can use to manage the recycle bin.

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 static methods for working with directories. The following table summarizes those static methods.

MethodPurpose
CreateDirectoryCreates a directory and any missing directories along its path.
DeleteDeletes a directory and its contents. It can recursively delete all subdirectories.
ExistsReturns true if the path points to an existing directory.
GetCreationTimeReturns a directory’s creation date and time.
GetCreationTimeUtcReturns a directory’s creation date and time in Coordinated Universal Time (UTC).
GetCurrentDirectoryReturns the application’s current working directory.
GetDirectoriesReturns an array of strings holding the fully qualified names of a directory’s subdirectories.
GetDirectoryRootReturns the directory root for a path, which need not exist (for example, C:).
GetFilesReturns an array of strings holding the fully qualified names of a directory’s files.
GetFileSystemEntriesReturns an array of strings holding the fully qualified names of a directory’s files and subdirectories.
GetLastAccessTimeReturns a directory’s last access date and time.
GetLastAccessTimeUtcReturns a directory’s last access date and time in UTC.
GetLastWriteTimeReturns the date and time when a directory was last modified.
GetLastWriteTimeUtcReturns the date and time when a directory was last modified in UTC.
GetLogicalDrivesReturns 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 drive but doesn’t list a flash drive after you disconnect it.
GetParentReturns a DirectoryInfo object representing a directory’s parent directory.
MoveMoves a directory and its contents to a new location on the same disk volume.
SetCreationTimeSets a directory’s creation date and time.
SetCreationTimeUtcSets a directory’s creation date and time in UTC.
SetCurrentDirectorySets the application’s current working directory.
SetLastAccessTimeSets a directory’s last access date and time.
SetLastAccessTimeUtcSets a directory’s last access date and time in UTC.
SetLastWriteTimeSets a directory’s last write date and time.
SetLastWriteTimeUtcSets a directory’s last write date and time in UTC.

File

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

MethodPurpose
AppendAllTextAdds text to the end of a file, creating the file if it doesn’t exist, and then closes the file.
AppendTextOpens a file for appending UTF-8 encoded text and returns a StreamWriter attached to it.
CopyCopies a file.
CreateCreates a new file and returns a FileStream attached to it.
CreateTextCreates or opens a file for writing UTF-8 encoded text and returns a StreamWriter attached to it.
DeletePermanently deletes a file.
ExistsReturns true if the specified file exists.
GetAttributesGets 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.
GetCreationTimeReturns a file’s creation date and time.
GetCreationTimeUtcReturns a file’s creation date and time in UTC.
GetLastAccessTimeReturns a file’s last access date and time.
GetLastAccessTimeUtcReturns a file’s last access date and time in UTC.
GetLastWriteTimeReturns a file’s last write date and time.
GetLastWriteTimeUtcReturns a file’s last write date and time in UTC.
MoveMoves a file to a new location.
OpenOpens 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.
OpenReadOpens a file for reading and returns a FileStream attached to it.
OpenTextOpens a UTF-8 encoded text file for reading and returns a StreamReader attached to it.
OpenWriteOpens a file for writing and returns a FileStream attached to it.
ReadAllBytesReturns a file’s contents in an array of bytes.
ReadAllLinesReturns a file’s lines in an array of strings.
ReadAllTextReturns a file’s contents in a string.
ReplaceThis 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.
SetAttributesSets 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.
SetCreationTimeSets a file’s creation date and time.
SetCreationTimeUtcSets a file’s creation date and time in UTC.
SetLastAccessTimeSets a file’s last access date and time.
SetLastAccessTimeUtcSets a file’s last access date and time in UTC.
SetLastWriteTimeSets a file’s last write date and time.
SetLastWriteTimeUtcSets a file’s last write date and time in UTC.
WriteAllBytesCreates or overwrites a file, writes an array of bytes into it, and closes the file.
WriteAllLinesCreates or overwrites a file, writes an array of strings into it, and closes the file.
WriteAllTextCreates 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.

PropertyPurposeMust Be Ready?
AvailableFreeSpaceReturns the amount of free space available on the drive in bytes. This value takes quotas into account, so it may not match TotalFreeSpace.True
DriveFormatReturns 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 www.ntfs.com/ntfs_vs_fat.htm compares the FAT, FAT32, and NTFS filesystems.)True
DriveTypeReturns a DriveType enumeration value indicating the drive type. This value can be CDRom, Fixed, Network, NoRootDirectory, Ram, Removable, or Unknown.False
IsReadyReturns true if the drive is ready. Many DriveInfo properties are unavailable and throw exceptions if you try to access them while the drive is not ready.False
NameReturns the drive’s name. This is the drive’s root name as in A: or C:.False
RootDirectoryReturns a DirectoryInfo object representing the drive’s root directory. See the following section, “DirectoryInfo,” for more information.False
TotalFreeSpaceReturns the total amount of free space on the drive in bytes.True
TotalSizeReturns the total amount of space on the drive in bytes.True
VolumeLabelGets 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 MethodPurpose
AttributesGets 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.
CreateCreates 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.
CreateSubdirectoryCreates 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.
CreationTimeGets or sets the directory’s creation time.
CreationTimeUtcGets or sets the directory’s creation time in UTC.
DeleteDeletes the directory if it is empty. A parameter lets you tell the object to delete its contents, too, if it isn’t empty.
ExistsReturns true if the directory exists.
ExtensionReturns the extension part of the directory’s name. Normally, this is an empty string for directories.
FullNameReturns the directory’s fully qualified path.
GetDirectoriesReturns 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.
GetFilesReturns 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.
GetFileSystemInfosReturns 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.
LastAccessTimeGets or sets the directory’s last access time.
LastAccessTimeUtcGets or sets the directory’s last access time in UTC.
LastWriteTimeGets or sets the directory’s last write time.
LastWriteTimeUtcGets or sets the directory’s last write time in UTC.
MoveToMoves the directory and its contents to a new path.
NameReturns the directory’s name without the path information.
ParentReturns a DirectoryInfo object representing the directory’s parent. If the directory is its filesystem’s root (for example, C:), this returns null.
RefreshRefreshes 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.
RootReturns a DirectoryInfo object representing the root of the directory’s filesystem.
ToStringReturns 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 MethodPurpose
AppendTextReturns a StreamWriter that appends text to the file.
AttributesGets 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.
CopyToCopies 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.
CreateCreates 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.
CreateTextCreates 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.
CreationTimeGets or sets the file’s creation time.
CreationTimeUtcGets or sets the file’s creation time in UTC.
DeleteDeletes the file.
DirectoryReturns a DirectoryInfo object representing the file’s directory.
DirectoryNameReturns the name of the file’s directory.
ExistsReturns true if the file exists.
ExtensionReturns the extension part of the file’s name including the period. For example, the extension for game.txt is .txt.
FullNameReturns the file’s fully qualified path and name.
IsReadOnlyReturns true if the file is marked read-only.
LastAccessTimeGets or sets the file’s last access time.
LastAccessTimeUtcGets or sets the file’s last access time in UTC.
LastWriteTimeGets or sets the file’s last write time.
LastWriteTimeUtcGets or sets the file’s last write time in UTC.
LengthReturns the number of bytes in the file.
MoveToMoves 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.
NameThe file’s name without the path information.
OpenOpens the file with specified 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.
OpenReadReturns a read-only FileStream attached to the file.
OpenTextReturns a StreamReader with UTF-8 encoding attached to the file for reading.
OpenWriteReturns a write-only FileStream attached to the file.
RefreshRefreshes 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.
ReplaceReplaces 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.
ToStringReturns 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.

PropertyPurpose
EnableRaisingEventsDetermines 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.
FilterDetermines 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 the FileSystemWatchers use the same event handlers.
IncludeSubdirectoriesDetermines whether the object watches subdirectories within the main path.
InternalBufferSizeDetermines the size of the internal buffer. If the watcher is monitoring an active directory, a small buffer may overflow.
NotifyFilterDetermines 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.
PathDetermines the path to watch.

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

MethodPurpose
DisposeReleases resources used by the object.
WaitForChangedSynchronously waits for a change to the target file or directory.

The following table summarizes the class’s events.

NameDescription
ChangedA file or subdirectory has changed.
CreatedA file or subdirectory was created.
DeletedA file or subdirectory was deleted.
ErrorThe watcher’s internal buffer overflowed.
RenamedA file or subdirectory was renamed.

Path

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

PropertyPurpose
AltDirectorySeparatorCharReturns the alternate character used to separate directory levels in a hierarchical path (typically /).
DirectorySeparatorCharReturns the character used to separate directory levels in a hierarchical path (typically , as in C:TestsBilling2010q2.dat).
InvalidPathCharsReturns 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.
PathSeparatorReturns the character used to separate path strings in environment variables (typically ;).
VolumeSeparatorCharReturns 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.

MethodPurpose
ChangeExtensionChanges a path’s extension.
CombineReturns two path strings concatenated. This does not simplify the result like the GetFullPath method does.
GetDirectoryNameReturns a path’s directory.
GetExtensionReturns a path’s extension.
GetFileNameReturns a path’s filename and extension.
GetFileNameWithoutExtensionReturns a path’s filename without the extension.
GetFullPathReturns 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.
GetInvalidFileNameCharsReturns a character array that holds characters that are not allowed in filenames.
GetPathRootReturns a path’s root directory string. For example, the statement Path.GetPathRoot("C:InvoicesUnpaidDeadbeats") returns C:.
GetRandomFileNameReturns a random filename.
GetTempFileNameCreates 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:UsersRodAppDataLocalTemp mpFCC6.tmp.
GetTempPathReturns the path to the system’s temporary folder. This is the path part of the filename returned by GetTempFileName.
HasExtensionReturns true if a path includes an extension.
IsPathRootedReturns true if a path is an absolute path. This includes TempWherever and C:ClientsLitigation, but not TempWherever or ..Uncle.

Special Folders

The System.Environment.SpecialFolder enumeration defines SpecialFolder objects representing folders such as MyDocuments, History, and CommonProgramFiles. Use a SpecialFolder object’s ToString method to get the folder’s name. Use Environment.GetFolderPath to get the directory’s path.

The following code lists special folders.

foreach (Environment.SpecialFolder folderType
    in Enum.GetValues(typeof(Environment.SpecialFolder)))
{
    Console.WriteLine(
        String.Format("{0,-25}{1}",
            folderType.ToString(),
            Environment.GetFolderPath(folderType)
        )
    );
}

Recycle Bin

C# doesn’t provide tools for working with the recycle bin, but you can manage the recycle bin by using a combination of three techniques: using the FileIO.FileSystem class, using API functions, and using Shell32.Shell.

FileIO.FileSystem

The Microsoft.VisualBasic.FileIO namespace includes a FileSystem class that provides DeleteDirectory and DeleteFile methods. Those methods can take an optional parameter that indicates whether you want to move the directory or file into the recycle bin, or whether you want to delete the directory or file permanently. (They can also take a parameter that lets you decide whether the methods should display progress dialogs.)

To use the FileSystem class to move files and directories into the recycle bin, add a reference to the Microsoft.VisualBasic library. Then use the class’s static DeleteFile and DeleteDirectory methods.

API Functions

The SHEmptyRecycleBin API function lets you empty the recycle bin. To use this function, add the following code to a class outside any methods.

[Flags]
private enum RecycleFlags : uint
{
    SHERB_NOCONFIRMATION = 0x1,
    SHERB_NOPROGRESSUI = 0x2,
    SHERB_NOSOUND = 0x4
}
[DllImport("shell32.dll")]
static extern int SHEmptyRecycleBin(
    IntPtr hWnd, string pszRootPath, uint dwFlags);

This code defines the RecycleFlags enumeration and the SHEmptyRecycleBin API function.

Now you can call the function, passing it appropriate parameters. The following EmptyRecycleBin method wraps the call to the API function to make it a bit easier to use.

public static void EmptyRecycleBin(bool showProgress, bool playSound,
    bool confirm)
{
    RecycleFlags options = 0;
    if (!showProgress) options |= RecycleFlags.SHERB_NOPROGRESSUI;
    if (!playSound) options |= RecycleFlags.SHERB_NOSOUND;
    if (!confirm) options |= RecycleFlags.SHERB_NOCONFIRMATION;

    SHEmptyRecycleBin(IntPtr.Zero, null, (uint)options);
}

This method uses its parameter values to compose an appropriate RecycleFlags value and then calls the API function.

Shell32.Shell

Shell32.Shell is an interface for working with the Windows shell. It enables you to interact with virtual objects representing such things as the recycle bin.

To use Shell32.Shell, first add a reference to “Microsoft Shell Controls And Automation” on the Reference Manager’s COM tab. To make using the Shell class easier, add the following using directive to the program.

using Shell32;

Now you can use code similar to the following to enumerate the files in the recycle bin.

const int RECYCLE_BIN_NAMESPACE = 10;

Shell shell = new Shell();
Folder bin = shell.NameSpace(RECYCLE_BIN_NAMESPACE);

// List the files.
foreach (FolderItem item in bin.Items())
{
    Console.WriteLine(item.Name + "
    " + item.Path);
}

This code creates a new Shell object and uses that object’s NameSpace method to get a Folder object representing the recycle bin. It then loops through the items returned by the Folder’s Items method, displaying each item’s name and path.

..................Content has been hidden....................

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