Is there a wildcard expansion option for .net apps?

crashmstr picture crashmstr · Dec 19, 2008 · Viewed 9.2k times · Source

I've used the setargv.obj linking for Expanding Wildcard Arguments in the past for a number of C and C++ apps, but I can't find any similar mention for .net applications.

Is there a standard way to have your app's command line parameters automatically wildcard expanded? (i.e. expand *.doc from one entry in args parameter to all that match that wildcard).

P.S. I've hacked something together with Directory.GetFiles() for my current little project, but it does not cover wildcards with paths (yet), and it would be nice to do it without custom code.

Update: here is my rough hack, for illustration. It needs to split the parameters for path and name for the GetFiles, but this is the general idea. Linking setargv.obj into a C or C++ app would basically do all the wildcard expansion, leaving the user to only iterate over the argv array.


static void Main(string[] args)
{
    foreach (String argString in args)
    {
        // Split into path and wildcard
        int lastBackslashPos = argString.LastIndexOf('\\') + 1;
        path = argString.Substring(0, lastBackslashPos);
        filenameOnly = argString.Substring(lastBackslashPos, 
                                   argString.Length - lastBackslashPos);

        String[] fileList = System.IO.Directory.GetFiles(path, filenameOnly);
        foreach (String fileName in fileList)
        {
            //do things for each file
        }
    }
}

Answer

tggagne picture tggagne · May 12, 2010

Here us my rough hack. I'd love for it to be recursive. And having experienced the shortcoming of Windows wildcards I might decide to use regular expressions rather than letting GetFiles() do it for me.

using System.IO;

public static string[] ExpandFilePaths(string[] args)
{
    var fileList = new List<string>();

    foreach (var arg in args)
    {
        var substitutedArg = System.Environment.ExpandEnvironmentVariables(arg);

        var dirPart = Path.GetDirectoryName(substitutedArg);
        if (dirPart.Length == 0)
            dirPart = ".";

        var filePart = Path.GetFileName(substitutedArg);

        foreach (var filepath in Directory.GetFiles(dirPart, filePart))
            fileList.Add(filepath);
    }

    return fileList.ToArray();
}