glob pattern matching in .NET

后端 未结 14 1444
遇见更好的自我
遇见更好的自我 2020-11-29 01:52

Is there a built-in mechanism in .NET to match patterns other than Regular Expressions? I\'d like to match using UNIX style (glob) wildcards (* = any number of any characte

14条回答
  •  青春惊慌失措
    2020-11-29 02:37

    The 2- and 3-argument variants of the listing methods like GetFiles() and EnumerateDirectories() take a search string as their second argument that supports filename globbing, with both * and ?.

    class GlobTestMain
    {
        static void Main(string[] args)
        {
            string[] exes = Directory.GetFiles(Environment.CurrentDirectory, "*.exe");
            foreach (string file in exes)
            {
                Console.WriteLine(Path.GetFileName(file));
            }
        }
    }
    

    would yield

    GlobTest.exe
    GlobTest.vshost.exe
    

    The docs state that there are some caveats with matching extensions. It also states that 8.3 file names are matched (which may be generated automatically behind the scenes), which can result in "duplicate" matches in given some patterns.

    The methods that support this are GetFiles(), GetDirectories(), and GetFileSystemEntries(). The Enumerate variants also support this.

提交回复
热议问题