Wednesday, May 26, 2004

Processing Command Line Wildcards

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 +.

4 comments:

  1. It's a bummer that Windows makes each application deal with wildcard expansion. In Unix, that's the job of the shell, which tends to make command line apps behave more uniformly.

    I've been looking for a better shell lately, by the way, and I've settled on the Hamilton C Shell, which rocks. It's a powerful way to work that is very well integrated with Windows. It's worth every penny.

    ReplyDelete
  2. Personally, I'm waiting for Monad. I've got myself to the point where cmd.exe is usable enough for me. But I'm cheap. :)

    ReplyDelete
  3. cmd.exe is good for me as well, considering I'm cheap as well. Is monad the next big thing in command line from MS? If so are they cooking up anything better by way of scripting?

    ReplyDelete
  4. Yes - Monad (any relation to Gonad?) is the next-gen command shell from MS. As for scripting, I hear it's going to support native .NET integration. Pretty sweet, if true - I'm just going on rumor at this point.

    For now, I find that NAnt makes for a pretty good general-purpose scripting environment for the things that cmd.exe batch files can't do easily.

    ReplyDelete