Reputation: 2952
I was wondering if anybody here could help me out as I'm still very new to C#. I have a drive with folders w/in folders w/in folders that all contain files. Is there a way to recursively loop through the files and gather up all of these file names into a .txt file?
I'm not sure how to implement this into my Console app--so does anybody have any code that might help?
Upvotes: 1
Views: 1566
Reputation: 25775
Now that I understand that you want to prompt the user for each file found, you may want to try something along these lines:
class Program
{
static IEnumerable<String> Visitor(String root, String searchPattern)
{
foreach (var file in Directory.GetFiles(root, searchPattern, SearchOption.TopDirectoryOnly))
{
yield return file;
}
foreach (var folder in Directory.GetDirectories(root))
{
foreach (var file in Visitor(folder, searchPattern))
yield return file;
}
}
static void Main(string[] args)
{
foreach (var file in Visitor(args[0], args[1]))
{
Console.Write("Process {0}? (Y/N) ", file);
if (Console.ReadKey().Key == ConsoleKey.Y)
{
Console.WriteLine("{1}\tProcessing {0}...", file, Environment.NewLine);
}
else
{
Console.WriteLine();
}
}
}
}
That will walk the directory structure and, for each match, prompt the user whether to process the file or not.
Upvotes: 4
Reputation: 999
Something like this maybe?
var files = Directory.GetFiles("c:\\", "*.*", SearchOption.AllDirectories);
using (var sw = new StreamWriter("output.txt"))
{
files.ToList().ForEach(file => sw.WriteLine(file));
}
Don't forget to Using System.IO
Upvotes: 3
Reputation: 258128
The C# Programming Guide has an article detailing both a recursive and an iterative approach to walk through a directory tree.
@Koen's answer is more useful in general, but the approaches in that article can be useful if you need a more "asynchronous" approach, where you update the UI (or whatever) each time you find a matching file. With the other approach, you either have all the files or you don't.
Upvotes: 3
Reputation: 3686
File.WriteAllLines("yourfile.txt", Directory.GetFiles("path", "*.*", SearchOption.AllDirectories));
Upvotes: 9