This appendix describes the .NET Framework’s filesystem classes. It also summarizes methods you can use to manage the recycle bin.
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.
The Directory
class provides static methods for working with directories. The following table summarizes those static methods.
Method | Purpose |
CreateDirectory | Creates a directory and any missing directories along its 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 drive but doesn’t list a flash drive 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. |
The File
class provides static methods for working with files. The following table summarizes its most useful static methods.
Method | Purpose |
AppendAllText | Adds text to the end of a file, creating the file 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 byte s. |
ReadAllLines | Returns a file’s lines in an array of string s. |
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. 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 byte s into it, and closes the file. |
WriteAllLines | Creates or overwrites a file, writes an array of string s into it, and closes the file. |
WriteAllText | Creates or overwrites a file, writes a string into it, and closes the file. |
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 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 throw exceptions if you try to access them while the drive is not ready. | False |
Name | Returns 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 following section, “DirectoryInfo,” 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 |
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 null . |
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. |
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 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. |
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. |
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 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 an 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. |
The Path
class provides static 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 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 ; ). |
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 like the GetFullPath method does. |
GetDirectoryName | Returns a path’s directory. |
GetExtension | Returns a path’s extension. |
GetFileName | Returns a path’s filename and extension. |
GetFileNameWithoutExtension | 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:UsersRodAppDataLocalTemp mpFCC6.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 . |
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)
)
);
}
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
.
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.
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
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.
3.135.212.29