C# 计算具有特定扩展名的文件数
:) 因此,我有一个硬件(我必须从控制台运行项目):我必须计算特定目录中的子目录数(用户以这种方式写入C# 计算具有特定扩展名的文件数,c#,file,directory,subdirectory,C#,File,Directory,Subdirectory,:) 因此,我有一个硬件(我必须从控制台运行项目):我必须计算特定目录中的子目录数(用户以这种方式写入“[path][extension][r]”) 因此,如果用户写入目录而不写入扩展名,我的程序只计算子目录的数量 但如果用户写入参数,例如.exe、.txt、.cs,我必须计算特定目录中具有此特定扩展名的文件数,并返回此数字 所以,第一部分一切都很好——我的程序工作正常,并且递归地(如果我写参数-r)或不(如果我不写)计算子目录的数量。问题是对扩展名为的文件进行计数 这是我计算子目录的函数: c
“[path][extension][r]”
)
因此,如果用户写入目录而不写入扩展名,我的程序只计算子目录的数量
但如果用户写入参数,例如.exe、.txt、.cs,我必须计算特定目录中具有此特定扩展名的文件数,并返回此数字
所以,第一部分一切都很好——我的程序工作正常,并且递归地(如果我写参数-r)或不(如果我不写)计算子目录的数量。问题是对扩展名为的文件进行计数
这是我计算子目录的函数:
class Data
{
public string curDir = Directory.GetCurrentDirectory();
public string Extension = "";
public bool isRecursive;
}
public static int CountDir(Data data)
{
string[] dirs = Directory.GetDirectories(data.curDir);
int res = dirs.Length;
int resFiles = files.Length;
try
{
if (data.isRecursive)
{
foreach (string subdir in dirs)
{
Data d = new Data();
d.curDir = subdir;
d.Extension = data.Extension;
d.isRecursive = data.isRecursive;
res += CountDir(d);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
return res;
}
所以我尝试用这种方法做类似的事情,但是对于文件,我有点困惑:
string[] files = Directory.GetFiles(data.curDir);
int resFiles = files.Length;
foreach (string ext in files)
{
FileInfo fi = new FileInfo(ext);
if (data.Extension != "")
{
if (fi.Extension == data.Extension)
{
//res = 0;
//++res;
//what am I supposed to do here?..
}
}
}
我还想知道我是否可以用同样的方法(CountDir)来实现这一点。
提前非常感谢
编辑:我知道SearchOptions.AllDirectories方法,但我事先不知道用户将写入哪个扩展名我会将文件计数逻辑放在自己的方法中,因为目标是获取特定目录而不是所有子目录的文件数。下面是一个基于示例代码的示例:
public static int countFiles(Data data)
{
string[] files = new string[0];
try
{
files = Directory.GetFiles(data.curDir, $"*{data.Extension}");
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
return files.Length;
}
我将把文件计数逻辑放在它自己的方法中,因为目标是获取特定目录而不是所有子目录的文件数。下面是一个基于示例代码的示例:
public static int countFiles(Data data)
{
string[] files = new string[0];
try
{
files = Directory.GetFiles(data.curDir, $"*{data.Extension}");
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
return files.Length;
}
这里有一个对
目录.GetFiles
的覆盖,你可以在其中包含一个搜索模式,如果它应该是递归的,你会递归地找到所有的txt文件。这里有一个对目录.GetFiles
的覆盖,你可以包含一个搜索模式,如果它应该是递归的,你会递归地找到所有的txt文件。