
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
712
|
Chapter 12: Filesystem I/O
DirectoryInfo mainDir = new DirectoryInfo(@"C:\TEMP ");
FileInfo[] items = mainDir.GetFiles(pattern);
foreach (FileInfo item in items)
{
Console.WriteLine("FILE: " + item.Name);
}
}
Discussion
If you need just an array of strings containing paths to both directories and files, you
can use the static method Directory.GetFileSystemEntries. The string array returned
does not include any information about whether an individual element is a directory
or a file. Each string element contains the entire path to either a directory or file con-
tained within the specified path.
To quickly and easily distinguish between directories and files, use the
Directory.
GetDirectories
and Directory.GetFiles static methods. These methods return arrays
of directory names and filenames. These methods return an array of string objects.
Each element contains the full path to the directory or file.
Returning a string is fine if you do not need any other information about the direc-
tory or file returned to you or if you are going to need more information for only one
of the files returned. It is more efficient to use the static methods to get the list of file-
names and just retrieve the
FileInfo for the ones you need than to have all of the
FileInfos constructed for the directory, ...