Reputation: 612
class FileSetGenerator
{
public static void FileSetGen(string[] arg, string path, string pattern, oout List<string> files)
{
int count = 0;
files = new List<string>();
if(arg.Contains("/R"))
{
Console.WriteLine("Called");
files.AddRange(Directory.GetFiles(path, pattern));
count++;
//List<string> dummy = new List<string>();
foreach (string file in files)
Console.WriteLine(file);
string[] dirs = Directory.GetDirectories(path);
foreach (string dir in dirs)
FileSetGen(arg, dir, pattern, out files);
}
else
files.AddRange(Directory.GetFiles(path, pattern));
}
}
I am trying to get all the files rooted at a specified directory(path) using this recursive call. So particularly i want to fill the List<> structure with all the files present in the pwd and it's sub-directories. But everytime the recursive function is called, the List<> structure gets hthe files of the sub-directory and the previous files gets over-written. Is there any way by which I can append the new data with each execution of the recursive call? I am coding in c#.
Upvotes: 0
Views: 162
Reputation: 30708
You need to pass initialized list to the first call of the function.
But seems like you are searching for all files with a pattern, in directory.
You can use Directory.GetFiles
overload that accepts SearchOption, which you can specify as AllDirectories to get files in all subfolders.
Upvotes: 1
Reputation: 35400
To fix this, use ref
instead of out
for the last parameter of your function and do not recreate it inside the function. Instead create the list once in the caller function and send it as ref parameter to this function. Directory.GetFiles()
however already does what you're trying to achieve.
Upvotes: 1