[英]Count the number of files with specific extension
:) :)
So I have a hw (I have to run project from console): I have to count the number of sub directories in specific directory (the user writes in this way " [path] [extension] [-r] "
) So if user writes the directory and doesn't write the extension, my program just counts the number of sub directories.所以我有一个硬件(我必须从控制台运行项目):我必须计算特定目录中子目录的数量(用户以这种方式写入
" [path] [extension] [-r] "
)所以如果用户写入目录而不写入扩展名,我的程序只计算子目录的数量。
BUT if user writes the parameter, for example, .exe, .txt, .cs, I have to count the number of files with this specific extension in the specific directory and return this number .但是,如果用户写入参数,例如 .exe、.txt、.cs,我必须计算特定目录中具有此特定扩展名的文件数并返回此数字。
Sooo, everything is good with the first part - my program works correctly and count the number of sub directories, recursively (if I write the parameter -r) or not (if I don't). Sooo,第一部分一切都很好 - 我的程序正常工作并计算子目录的数量,递归(如果我写参数 -r)或不(如果我不写)。 The problem is with counting files with extension.
问题在于计算带有扩展名的文件。
Here is my function for counting sub directories :这是我计算子目录的函数:
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;
}
So I tried to do the similar thing in this method, but for files and I'm a bit confused:所以我尝试在这种方法中做类似的事情,但是对于文件,我有点困惑:
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?..
}
}
}
I also wonder if I can do this in the same method (CountDir).我也想知道我是否可以用相同的方法 (CountDir) 做到这一点。 Thank you so much in advance!
非常感谢您!
Edit : I know about SearchOptions.AllDirectories method, but I don't know in advance which extension user will write编辑:我知道 SearchOptions.AllDirectories 方法,但我事先不知道用户会写哪个扩展
I would put the file count logic in its own method since the goal is to get the number of files for a specific directory rather than all sub-directories.我会将文件计数逻辑放在自己的方法中,因为目标是获取特定目录而不是所有子目录的文件数。 Here's an example based on your sample code:
这是基于您的示例代码的示例:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.