code_junkie

How to implement glob in C#

Nov 13th, 2011
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. /// <summary>
  2. /// return a list of files that matches some wildcard pattern, e.g.
  3. /// C:p4softwaredotnettools**.sln to get all tool solution files
  4. /// </summary>
  5. /// <param name="glob">pattern to match</param>
  6. /// <returns>all matching paths</returns>
  7. public static IEnumerable<string> Glob(string glob)
  8. {
  9. foreach (string path in Glob(PathHead(glob) + DirSep, PathTail(glob)))
  10. yield return path;
  11. }
  12.  
  13. /// <summary>
  14. /// uses 'head' and 'tail' -- 'head' has already been pattern-expanded
  15. /// and 'tail' has not.
  16. /// </summary>
  17. /// <param name="head">wildcard-expanded</param>
  18. /// <param name="tail">not yet wildcard-expanded</param>
  19. /// <returns></returns>
  20. public static IEnumerable<string> Glob(string head, string tail)
  21. {
  22. if (PathTail(tail) == tail)
  23. foreach (string path in Directory.GetFiles(head, tail).OrderBy(s => s))
  24. yield return path;
  25. else
  26. foreach (string dir in Directory.GetDirectories(head, PathHead(tail)).OrderBy(s => s))
  27. foreach (string path in Glob(Path.Combine(head, dir), PathTail(tail)))
  28. yield return path;
  29. }
  30.  
  31. /// <summary>
  32. /// shortcut
  33. /// </summary>
  34. static char DirSep = Path.DirectorySeparatorChar;
  35.  
  36. /// <summary>
  37. /// return the first element of a file path
  38. /// </summary>
  39. /// <param name="path">file path</param>
  40. /// <returns>first logical unit</returns>
  41. static string PathHead(string path)
  42. {
  43. // handle case of \sharevolfoobar -- return \sharevol as 'head'
  44. // because the dir stuff won't let you interrogate a server for its share list
  45. // FIXME check behavior on Linux to see if this blows up -- I don't think so
  46. if (path.StartsWith("" + DirSep + DirSep))
  47. return path.Substring(0, 2) + path.Substring(2).Split(DirSep)[0] + DirSep + path.Substring(2).Split(DirSep)[1];
  48.  
  49. return path.Split(DirSep)[0];
  50. }
  51.  
  52. /// <summary>
  53. /// return everything but the first element of a file path
  54. /// e.g. PathTail("C:TEMPfoo.txt") = "TEMPfoo.txt"
  55. /// </summary>
  56. /// <param name="path">file path</param>
  57. /// <returns>all but the first logical unit</returns>
  58. static string PathTail(string path)
  59. {
  60. if (!path.Contains(DirSep))
  61. return path;
  62.  
  63. return path.Substring(1 + PathHead(path).Length);
  64. }
Add Comment
Please, Sign In to add comment