I can use a keyboard so much faster than a mouse that I just hate it when an app makes me click things instead of letting me type in shortcuts. So it's no surprise that I love working at the command line. One thing that distinguishes a good command line application from a bad one is whether or not it lets you use wildcards. For example, being able to do:
fooutil blah.txt *.cs abc????.xml
is a good thing - it lets me say, “Run fooutil on the file blah.txt, any file with a .cs extension, and files that have a name that start with abc, are seven characters long, and have an xml extension” all in one fell swoop.
As it turns out, getting this behavior in your app is pretty easy. Here's the code:
public static int Main(
string[] args) {
foreach (
string filespec
in args) {
string specdir =
Path.GetDirectoryName(filespec);
string specpart =
Path.GetFileName(filespec);
// GetFiles will vomit on an empty specdir if (specdir.Length == 0) {
specdir =
Environment.CurrentDirectory;
}
foreach (
string file
in Directory.GetFiles(specdir, specpart)) {
string path =
Path.Combine(specdir, file);
// Your code to process the file identified by path goes here
}
}
}
The key magic here is Directory.GetFiles, which will return you a string array of file names that match a given directory a pattern. Check out the docs for Directory.GetFiles to get the full scoop on what patterns are legal. Also note the use of Path.Combine - never combine path elements with +.
Posted
May 26 2004, 10:17 AM
by
craig-andera