我用过 setargv.obj
linking for Expanding Wildcard Arguments过去有很多 C 和 C++ 应用程序,但我找不到任何类似的 .net 应用程序。
是否有一种标准方法可以让您的应用的命令行参数自动扩展通配符?(即将 *.doc
从 args 参数中的一个条目扩展到所有匹配的条目通配符)。
附言我已经为我当前的小项目与 Directory.GetFiles()
一起破解了一些东西,但它不包括带路径的通配符(目前),如果没有自定义代码就很好。
更新:这是我的粗略技巧,用于说明。它需要为 GetFiles()
拆分路径参数和名称参数,但这是一般的想法。将 setargv.obj
链接到 C 或 C++ 应用程序基本上会完成所有通配符扩展,让用户只能迭代 argv 数组。
public 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
}
}
}
最佳答案
这是我的粗略技巧。我希望它是递归的。在经历了 Windows 通配符的缺点之后,我可能决定使用正则表达式而不是让 GetFiles() 为我做这件事。
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();
}
关于c# - .net 应用程序是否有通配符扩展选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/381366/