As the title says I'm trying to count the number of file in a directory and subdirectories. I tried with a foreach loop like that :
public static int hello(string path)
{
string[] files = Directory.GetFiles(path);
string[] dirs = Directory.GetDirectories(path);
int cpt = 0;
foreach (var file in files)
{
try
{
Console.WriteLine(file);
cpt ;
}
catch { }
}
foreach (var directory in dirs)
{
try
{
hello(directory);
}
catch { }
}
return cpt;
}
And the returned value is always the number of file contained in the first path, the cpt var don't get incremented by the number of files in the others directories and subdirectories.
It's strange since the Console.WriteLine(file) shows all the files path in the console box.
It looks like a small issue but I don't really know how to solve it, I don't want to use SearchOption method but I really want to use cpt and increment it at each file.
CodePudding user response:
SOLVED with the following code :
public static int hello(string path)
{
string[] files = Directory.GetFiles(path);
string[] dirs = Directory.GetDirectories(path);
int cpt = 0;
foreach (var file in files)
{
try
{
Console.WriteLine(file);
cpt ;
}
catch { }
}
foreach (var directory in dirs)
{
try
{
cpt =hello(directory);
}
catch { }
}
return cpt;
}
Thanks to @steryd !
CodePudding user response:
When you descend down the directories you're not saving the count. cpt is unique for each invocation of hello()