返回子文件夹的数量C#

时间:2013-12-30 10:30:00

标签: c#

我有一个非常基本的WinForms应用程序,用于搜索用户选择的指定文件夹中的文件数。代码是:

        DialogResult result = folderBrowserDialog1.ShowDialog();
        if (result == DialogResult.OK)
        {
            if (checkSubFolders.Checked = !true)
            {
                string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
                txbNumberOfFiles.Text = files.Length.ToString();
                txbFilePath.Text = folderBrowserDialog1.SelectedPath;
            }

现在,当我勾选复选框时,我想要做的还是返回子文件夹中的文件数。有一种简单的方法吗?感谢

4 个答案:

答案 0 :(得分:0)

DirectoryInfo di = new DirectoryInfo("PATH");

var subDirs = di.GetDirectories;

然后计算/返回返回的数组..应该这样做......

答案 1 :(得分:0)

您可以指定SearchOption.AllDirectories以递归方式搜索:

SearchOption searchOption = checkSubFolders.Checked ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*", searchOption);
txbNumberOfFiles.Text = files.Length.ToString();
txbFilePath.Text = folderBrowserDialog1.SelectedPath;

答案 2 :(得分:0)

所以我觉得你总会得到文件吗?

如果是,那么你可以删除该部分的if语句。

DialogResult result = folderBrowserDialog1.ShowDialog();
    if (result == DialogResult.OK)
    {
            string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
            txbNumberOfFiles.Text = files.Length.ToString();
            txbFilePath.Text = folderBrowserDialog1.SelectedPath;

            if(checkSubFolders.Checked)
            {
                 //You can do the same as before here with Directory.GetFiles();
                 Directory.GetDirectories(path, "*", SearchOption.AllDirectories).Count();
                 //Gets the number of files in subfolders and so on. Ofcourse you would have to parametrise path.

            }
    }

如果您不想删除if语句,那么您可以执行If / Else,但是您将复制代码,所以至少我会把这部分:

string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
        txbNumberOfFiles.Text = files.Length.ToString();
        txbFilePath.Text = folderBrowserDialog1.SelectedPath;

进入它自己的方法,然后在if / else

中调用该方法

答案 3 :(得分:0)

您正在寻找此

SearchOption option = SearchOption.TopDirectoryOnly;
if (checkSubFolders.Checked)
    option = SearchOption.AllDirectories;

int totalFiles  = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", option).Length;