You want to recurse through directories to find file names using the C# programming language. Find all files and folders at a specified level on the disk, and then everything within that. There is an algorithm on MSDN, but it has some shortcomings. Use the method shown here or some parts of it for your solution, using the C# programming language.
=== Requirements for file and directory method in C# === You specify one directory path. The method returns all subdirectories/files recursively. Result paths are stored in List<string> See simpler implementation in "Alternatives" below. Input directory: C:\ Output paths: C:\File.txt C:\Word.doc C:\Data.xml C:\Directory\List.txt C:\Directory\ID.txt C:\Directory\More\Summary.doc C:\Random\Number.txt
Here is a the directory recursion algorithm that doesn't actually use true recursion, but instead uses a Stack. We call the Directory.GetFiles method, which returns all the file names in a directory. Then, we use the Directory.GetDirectories for the list of all directories at each level.
~~~ Program that recurses through folders (C#) ~~~
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
static void Main()
{
// Get all files in Documents
List<string> dirs = FileHelper.GetFilesRecursive(@"C:\Users\Sam\Documents");
foreach (string p in dirs)
{
Console.WriteLine(p);
}
// Write count
Console.WriteLine("Count: {0}", dirs.Count);
Console.Read();
}
}
static class FileHelper
{
public static List<string> GetFilesRecursive(string b)
{
// 1.
// Store results in the file results list.
List<string> result = new List<string>();
// 2.
// Store a stack of our directories.
Stack<string> stack = new Stack<string>();
// 3.
// Add initial directory.
stack.Push(b);
// 4.
// Continue while there are directories to process
while (stack.Count > 0)
{
// A.
// Get top directory
string dir = stack.Pop();
try
{
// B
// Add all files at this directory to the result List.
result.AddRange(Directory.GetFiles(dir, "*.*"));
// C
// Add all directories at this directory.
foreach (string dn in Directory.GetDirectories(dir))
{
stack.Push(dn);
}
}
catch
{
// D
// Could not open the directory
}
}
return result;
}
}
~~~ Output of the program ~~~
The result will be the total count of the files.Code example description. The above code sample first has the Main method, which specifies that GetFilesRecursive looks through my personal Documents folder. It loops through all the directories found and then writes the Count from the List.
Steps taken. GetFilesRecursive instantiates a List<string> to store the results of the directory recursion. You could enhance this by specifying a capacity. In step 2, it creates a Stack here and then in part 3, adds the parameter directory path b to the Stack first. Stacks allow you to process the top item in the collection, then remove it or add more. This replaces true recursion.
Next step. In part 4, it continues looping in the while loop as long as there are strings in the Stack. This means all directory paths are processed before the loop exits. Inside the loop, it Pops the directory name Stack, meaning it takes the top string from the collection. This is the directory path we want to use in the current iteration.
Part B description. It uses AddRange with all the files. We call AddRange on the List to append all the files at this level in the directory, with no filter specified, to the List. AddRange adds the string[] array to the end of the List. This part of the code also uses the Directory.GetFiles method.
Part C. All directory paths are added to the Stack. This means we will deal with the directories in the loop in reverse order. We avoid recursion, which means we process the directories in a different order.
Part D. It catches IOExceptions, which can occur in many different scenarios. In your deployed program, you will want to log these and have more robust exception-handling. For simpler programs, exception handling is not as critical.
The directory recursion method GetFilesRecursive returns a List<string> generic, meaning it requires C# 2.0, which most organizations use now. In your program, you may need a string[] array instead of a List. The two can be converted readily.
As a test, I specified my personal Documents folder, C:\Users\Sam\Documents. The output below shows the program reporting that I had 4677 files in my Documents folder. Windows Vista also reports that there were 4677 files in my Documents folder. Note that the paths are added without any processing, so they should never be mangled.
C:\Users\Sam\Documents\Downloads\jpeg-6b-4-bin\bin\exifautotran C:\Users\Sam\Documents\Downloads\jpeg-6b-4-bin\bin\jpeg62.dll C:\Users\Sam\Documents\Downloads\jpeg-6b-4-bin\bin\jpegexiforient.exe C:\Users\Sam\Documents\Downloads\jpeg-6b-4-bin\bin\jpegtran.exe C:\Users\Sam\Documents\Downloads\jpeg-6b-4-bin\bin\rdjpgcom.exe C:\Users\Sam\Documents\Downloads\jpeg-6b-4-bin\bin\wrjpgcom.exe Count: 4677 Press any key to continue . . .
We use Stack to avoid problems associated with other methods. Stacks in programming are the same as stacks in real life. We "collect" all the directories in the Stack, and then process them one by one. This avoids recursion and means we don't have to deal with reentrancy and other hard stuff. It is easier to debug, and may also be more efficient in some scenarios.
(See Stack Usage, Methods and Tips.)
Microsoft helpfully provides a directory recursion method on MSDN. However, it has different characteristics. It uses true recursion, which is an overall negative due to the higher complexity and reduced flexibility. Not only that, but the MSDN method skips the directory you pass to it and simply looks to subdirectories.
(Visit support.microsoft.com.)
Built-in framework methods. In this section we note that the .NET Framework now contains an overload of the Directory.GetFiles method that accepts a parameter enumeration that can be equal to the enumerated constant SearchOption.AllDirectories. This method collects all the directories recursively and the set of results is the same as the method shown in this article, but in a different order.
(See Recursive File List [SearchOption.AllDirectories].)
Here we saw how you can recursively scan folders for filenames, using the C# language. Using Stack to simulate recursion is a performance boost and improves simplicity. Here we saw how to loop through all directories and subdirectories and collect the file names. The method is static and can easily be dropped into a helper utility class or used directly in small projects.