How to implement glob in C#

后端 未结 4 697
逝去的感伤
逝去的感伤 2020-11-28 10:18

I don\'t know if it\'s legit at StackOverflow to post your own answer to a question, but I saw nobody had asked this already. I went looking for a C# Glob and didn\'t find

4条回答
  •  无人及你
    2020-11-28 10:32

        /// 
        /// return a list of files that matches some wildcard pattern, e.g. 
        /// C:\p4\software\dotnet\tools\*\*.sln to get all tool solution files
        /// 
        /// pattern to match
        /// all matching paths
        public static IEnumerable Glob(string glob)
        {
            foreach (string path in Glob(PathHead(glob) + DirSep, PathTail(glob)))
                yield return path;
        }
    
        /// 
        /// uses 'head' and 'tail' -- 'head' has already been pattern-expanded
        /// and 'tail' has not.
        /// 
        /// wildcard-expanded
        /// not yet wildcard-expanded
        /// 
        public static IEnumerable Glob(string head, string tail)
        {
            if (PathTail(tail) == tail)
                foreach (string path in Directory.GetFiles(head, tail).OrderBy(s => s))
                    yield return path;
            else
                foreach (string dir in Directory.GetDirectories(head, PathHead(tail)).OrderBy(s => s))
                    foreach (string path in Glob(Path.Combine(head, dir), PathTail(tail)))
                        yield return path;
        }
    
        /// 
        /// shortcut
        /// 
        static char DirSep = Path.DirectorySeparatorChar;
    
        /// 
        /// return the first element of a file path
        /// 
        /// file path
        /// first logical unit
        static string PathHead(string path)
        {
            // handle case of \\share\vol\foo\bar -- return \\share\vol as 'head'
            // because the dir stuff won't let you interrogate a server for its share list
            // FIXME check behavior on Linux to see if this blows up -- I don't think so
            if (path.StartsWith("" + DirSep + DirSep))
                return path.Substring(0, 2) + path.Substring(2).Split(DirSep)[0] + DirSep + path.Substring(2).Split(DirSep)[1];
    
            return path.Split(DirSep)[0];
        }
    
        /// 
        /// return everything but the first element of a file path
        /// e.g. PathTail("C:\TEMP\foo.txt") = "TEMP\foo.txt"
        /// 
        /// file path
        /// all but the first logical unit
        static string PathTail(string path)
        {
            if (!path.Contains(DirSep))
                return path;
    
            return path.Substring(1 + PathHead(path).Length);
        }
    

提交回复
热议问题