我需要计算此递归函数中删除的文件数。由于它是递归的,我不能使用if
语句,而C#不支持全局变量。任何替代方案?
static void DirSearch(string path)
{
try
{
foreach (string dirPath in Directory.GetDirectories(path))
{
foreach (string filePath in Directory.GetFiles(dirPath))
{
string filename = Path.GetFileName(filePath);
if (filename.Equals("desktop.txt"))
{
File.Delete(filePath);
//count++
}
Console.WriteLine(filePath); // print files
}
Console.WriteLine(dirPath); // print directories
DirSearch(dirPath);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}
答案 0 :(得分:8)
尝试递归count
,如下所示。因此DirSearch
会返回已删除文件的count
。
static int DirSearch(string path)
{
int count = 0;
try
{
foreach (string dirPath in Directory.GetDirectories(path))
{
foreach (string filePath in Directory.GetFiles(dirPath))
{
string filename = Path.GetFileName(filePath);
if (filename.Equals("desktop.txt"))
{
File.Delete(filePath);
count++;
}
Console.WriteLine(filePath); // print files
}
Console.WriteLine(dirPath); // print directories
count += DirSearch(dirPath);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
return count;
}
答案 1 :(得分:7)
一种方法是传递一些东西让它计入。我会使用ref
执行此操作,例如:
static void DirSearch(string path, ref int count)
{
try
{
foreach (string dirPath in Directory.GetDirectories(path))
{
foreach (string filePath in Directory.GetFiles(dirPath))
{
string filename = Path.GetFileName(filePath);
if (filename.Equals("desktop.txt"))
{
File.Delete(filePath);
count++
}
Console.WriteLine(filePath); // print files
}
Console.WriteLine(dirPath); // print directories
DirSearch(dirPath,ref count);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}
然后叫它:
int count = 0;
DirSearch(@"C:\SomePath",ref count);
然后,您可以正常使用count
,就像您在代码中注释掉一样。
答案 2 :(得分:2)
没有ref变量(因此您不需要传递正确初始化的内容):
static int DirSearch(string path)
{
try
{
int count = 0;
foreach (string dirPath in Directory.GetDirectories(path))
{
foreach (string filePath in Directory.GetFiles(dirPath))
{
string filename = Path.GetFileName(filePath);
if (filename.Equals("desktop.txt"))
{
File.Delete(filePath);
count++;
}
Console.WriteLine(filePath); // print files
}
Console.WriteLine(dirPath); // print directories
count += DirSearch(dirPath);
}
return count;
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}
答案 3 :(得分:0)
您是否也考虑过这里提出的非递归解决方案? https://stackoverflow.com/a/929418/2979680