Comment mettre en œuvre glob in C#

Je ne sais pas si C'est légal à StackOverflow de poster votre propre réponse à une question, mais j'ai vu que personne ne l'avait déjà demandé. J'ai cherché un C # Glob et je n'en ai pas trouvé, alors j'en ai écrit un que d'autres pourraient trouver utile.

19
demandé sur Mark Maxham 2008-12-29 23:02:21

3 réponses

    /// <summary>
    /// return a list of files that matches some wildcard pattern, e.g. 
    /// C:\p4\software\dotnet\tools\*\*.sln to get all tool solution files
    /// </summary>
    /// <param name="glob">pattern to match</param>
    /// <returns>all matching paths</returns>
    public static IEnumerable<string> Glob(string glob)
    {
        foreach (string path in Glob(PathHead(glob) + DirSep, PathTail(glob)))
            yield return path;
    }

    /// <summary>
    /// uses 'head' and 'tail' -- 'head' has already been pattern-expanded
    /// and 'tail' has not.
    /// </summary>
    /// <param name="head">wildcard-expanded</param>
    /// <param name="tail">not yet wildcard-expanded</param>
    /// <returns></returns>
    public static IEnumerable<string> 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;
    }

    /// <summary>
    /// shortcut
    /// </summary>
    static char DirSep = Path.DirectorySeparatorChar;

    /// <summary>
    /// return the first element of a file path
    /// </summary>
    /// <param name="path">file path</param>
    /// <returns>first logical unit</returns>
    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];
    }

    /// <summary>
    /// return everything but the first element of a file path
    /// e.g. PathTail("C:\TEMP\foo.txt") = "TEMP\foo.txt"
    /// </summary>
    /// <param name="path">file path</param>
    /// <returns>all but the first logical unit</returns>
    static string PathTail(string path)
    {
        if (!path.Contains(DirSep))
            return path;

        return path.Substring(1 + PathHead(path).Length);
    }
14
répondu Mark Maxham 2008-12-29 20:03:51

je suis tombé sur la source pour repasser ruby qui contient une classe de Glob assez soignée. C'est assez facile de l'extraire du code correspondant.

https://github.com/IronLanguages/main/blob/master/Languages/Ruby/Ruby/Builtins/Glob.cs

2
répondu Andreas 2012-08-31 11:46:30

vous pouvez utiliser le cmdlet" dir "(alias" Get-ChildItem") powershell de C#.

(Je ne dis pas si vous devriez.)

vous devez ajouter cette référence à votre dossier de projet (" .csproj " ou .vcproj") manuellement:

<Reference Include="System.Management.Automation" />

voir ici pour plus de détails sur la façon d'utiliser cmdlets de C#: http://www.devx.com/tips/Tip/42716

ici un travail programme:

using System;
using System.Collections.Generic;

using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;

namespace CsWildcard {
    class Program {

        static IEnumerable<string> CmdletDirGlobbing(string basePath, string glob){
            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();

            // cd to basePath
            if(basePath != null){
                Pipeline cdPipeline = runspace.CreatePipeline();
                Command cdCommand = new Command("cd");
                cdCommand.Parameters.Add("Path", basePath);
                cdPipeline.Commands.Add(cdCommand);
                cdPipeline.Invoke(); // run the cmdlet
            }

            // run the "dir" cmdlet (e.g. "dir C:\*\*\*.txt" )
            Pipeline dirPipeline = runspace.CreatePipeline();
            Command dirCommand = new Command("dir");
            dirCommand.Parameters.Add("Path", glob);
            dirPipeline.Commands.Add(dirCommand);

            Collection<PSObject> dirOutput = dirPipeline.Invoke();

            // for each found file
            foreach (PSObject psObject in dirOutput) {

                PSMemberInfoCollection<PSPropertyInfo> a = psObject.Properties;
                // look for the full path ("FullName")
                foreach (PSPropertyInfo psPropertyInfo in psObject.Properties) {
                    if (psPropertyInfo.Name == "FullName") {
                        yield return psPropertyInfo.Value.ToString(); // yield it
                    }
                }
            }

        }

        static void Main(string[] args) {
            foreach(string path in CmdletDirGlobbing(null,"C:\*\*\*.txt")){
                System.Console.WriteLine(path);
            }
            foreach (string path in CmdletDirGlobbing("C:\", "*\*\*.exe")) {
                System.Console.WriteLine(path);
            }   
            Console.ReadKey();
        }

    }
}
0
répondu Robert Fey 2013-08-27 15:31:33