get files recursively


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. namespace Kyrathasoft.FilesDirectories.GetFilesRecursively {
  2.  
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6.  
  7. public static class clsGetFilesRecursively {
  8.  
  9. public static List<string> GetFilesRecursively(string b) {
  10.  
  11. // 1.Store results in the file results list.
  12. List<string> result = new List<string>();
  13.  
  14. // 2.Store a stack of our directories.
  15. Stack<string> stack = new Stack<string>();
  16.  
  17. // 3.Add initial directory.
  18. stack.Push(b);
  19.  
  20. // 4.Continue while there are directories to process
  21. while (stack.Count > 0) {
  22. // A.Get top directory
  23. string dir = stack.Pop();
  24.  
  25. try {
  26. // B. Add all files at this directory to the result List.
  27. result.AddRange(Directory.GetFiles(dir, "*.*"));
  28.  
  29. // C. Add all directories at this directory.
  30. foreach (string dn in Directory.GetDirectories(dir)) {
  31. stack.Push(dn);
  32. }
  33. }
  34. catch {
  35. // D. Could not open the directory
  36. }
  37. }
  38. return result;
  39. }
  40.  
  41.  
  42. public static int getNumOfSubdirs(string topLvDir) {
  43.  
  44. int totalSubdirs = 0;
  45.  
  46. //Store a stack of our directories.
  47. Stack<string> stack = new Stack<string>();
  48.  
  49. //Add initial directory.
  50. stack.Push(topLvDir);
  51.  
  52. //Continue while there are directories to process
  53. while (stack.Count > 0) {
  54. //Get top directory
  55. string dir = stack.Pop();
  56.  
  57. try {
  58. //Add all directories at this directory.
  59. foreach (string dn in Directory.GetDirectories(dir)) {
  60. totalSubdirs++;
  61. }
  62. }
  63. catch {
  64. // D. Could not open the directory
  65. }
  66. }
  67. return totalSubdirs;
  68.  
  69. }
  70.  
  71. }
  72.  
  73.  
  74.  
  75. public class encappedListOfStrings {
  76. public encappedListOfStrings() { }
  77. public encappedListOfStrings(List<string> the_list) {
  78. _listOfStrings = the_list;
  79. }
  80. private List<string> _listOfStrings;
  81. public List<string> ListOfStrings {
  82. get { return _listOfStrings; }
  83. }
  84. }
  85.  
  86.  
  87. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.