C# 返回子文件夹C的数目

C# 返回子文件夹C的数目,c#,C#,我有一个非常基本的WinForms应用程序,可以搜索用户选择的指定文件夹中的文件数。代码是: DialogResult result = folderBrowserDialog1.ShowDialog(); if (result == DialogResult.OK) { if (checkSubFolders.Checked = !true) { string[] f

我有一个非常基本的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;
            }
现在我要做的是,选中“我的”复选框时,返回子文件夹中的文件数。有没有一种简单化的方法?谢谢

DirectoryInfo di=新目录InfoPath

var subDirs=di.GetDirectories;

然后对返回的数组进行计数。。这样就可以了…

您可以指定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;

所以我的印象是你会一直得到这些文件

如果是,则可以删除该部分的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中调用该方法

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

int totalFiles  = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", option).Length;
如果选中子文件夹,则可能需要修复此问题。选中=!符合事实的现在它实际上是将false赋值给Checked属性。你可能是说如果选中子文件夹.Checked。