c# - .net 应用程序是否有通配符扩展选项?

标签 c# .net vb.net wildcard

我用过 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/

相关文章:

c# - Blazor 发布和响应 C#

C# MySQLDriverCS - 插入/更新中的“字符”

c# - 只要层次结构中的所有类仅使用托管资源,就可以使用虚拟 Dispose() 方法吗?

c# - EntityFramework 中的公用表表达式

c# - 检查网络驱动器上是否存在目录

javascript - 从 aspx 中的代码隐藏调用 JavaScript

c# - 试图把我的头缠绕在线程上

.net - Microsoft.Data.Tools.Schema.Sql.UnitTesting 程序集的程序集冲突解决

c# - x64 上的文件时间

.net - 从 VB.NET 中的电子邮件附件获取复制到剪贴板的文件名