The MSDN documentation for the Directory.GetFiles Method (String, String, SearchOption) includes this note:
When you use the asterisk wildcard character in a searchPattern such
as "*.txt", the number of characters in the specified extension
affects the search as follows:
•If the specified extension is exactly three characters long, the
method returns files with extensions that begin with the specified
extension. For example, "*.xls" returns both "book.xls" and
"book.xlsx".
•In all other cases, the method returns files that exactly match the
specified extension. For example, "*.ai" returns "file.ai" but not
"file.aif".
When you use the question mark wildcard character, this method returns
only files that match the specified file extension. For example, given
two files, "file1.txt" and "file1.txtother", in a directory, a search
pattern of "file?.txt" returns just the first file, whereas a search
pattern of "file*.txt" returns both files.
The easiest way to work around Microsoft being "helpful" in this manner is to filter the results of the Directory.GetFiles
call:
string[] files = Directory.GetFiles(filesPath, "*.doc", SearchOption.AllDirectories);
foreach (string f in files.Where(f => Path.GetExtension(f) == ".doc"))
{
File.Delete(f);
}
I renamed your Path
variable because it clashes with the System.IO.Path
class which holds the static GetExtension
method. As a general rule of thumb, giving variables the same name as existing classes is a bad habit.