【问题标题】:Count the number of files with specific extension计算具有特定扩展名的文件数
【发布时间】:2021-02-14 01:10:00
【问题描述】:

:)

所以我有一个硬件(我必须从控制台运行项目):我必须计算特定目录中子目录的数量(用户这样写" [path] [extension] [-r] ") 所以如果用户写了目录而不写扩展名,我的程序只计算子目录的数量。

但是如果用户写入参数,例如.exe、.txt、.cs,我必须统计特定目录中具有此特定扩展名的文件的数量并返回此数量

Sooo,第一部分一切都很好 - 我的程序正常工作并递归计算子目录的数量(如果我写参数 -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 方法,但我事先不知道哪个扩展用户会写

【问题讨论】:

标签: c# file directory subdirectory


【解决方案1】:

我会将文件计数逻辑放在它自己的方法中,因为目标是获取特定目录而不是所有子目录的文件数。这是基于您的示例代码的示例:

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;
}

【讨论】:

    猜你喜欢
    • 2010-11-22
    • 2011-06-30
    • 1970-01-01
    • 2010-12-28
    • 1970-01-01
    • 2017-05-09
    • 2020-06-06
    • 2011-02-14
    • 1970-01-01
    相关资源
    最近更新 更多