从子目录检索特定的文件类型

本文关键字:文件 类型 子目录 检索 | 更新日期: 2023-09-27 18:24:21

我有一个Winforms应用程序。我有一个文件夹浏览器、文本框1和两个按钮控件。

在我的文件夹里,我有很多子文件夹,每个hahing都有更多的子文件夹。我想从一个命名的子目录中选择文件类型,并在上调用它

string[] dirs = 
               Directory.GetDirectories(textBox1.Text, "p*", SearchOption.TopDirectoryOnly); 

并打印文件类型。我面临的问题是我从根目录而不是从子目录获取文件。

private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
            folderBrowserDlg.ShowNewFolderButton = true;
            DialogResult dlgResult = folderBrowserDlg.ShowDialog();
            if (dlgResult.Equals(DialogResult.OK))
            {
                textBox1.Text = folderBrowserDlg.SelectedPath;
                Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
            }
        } 
    private void button3_Click(object sender, EventArgs e)
        {
            var file = System.IO.Directory.EnumerateFiles(textBox1.Text, "*.*", SearchOption.AllDirectories)
            .Where(s => s.EndsWith(".html") || s.EndsWith(".mp3") || s.EndsWith(".png"));
            string[] files = Directory.GetFiles(textBox1.Text);
            string[] dirs = Directory.GetDirectories(textBox1.Text,"file");

            foreach (var a in dirs)
            {
                listBox1.Items.Add(a);
            }
            foreach (string item2 in dirs)
            {
                FileInfo f = new FileInfo(item2);
                listBox1.Items.Add(f.Name);
            }
            foreach (string item in files)
            {
                FileInfo f = new FileInfo(item);
                listBox1.Items.Add(f.Name);
            }
        }

从子目录检索特定的文件类型

我上周做了:

private void button1_Click(object sender, EventArgs e)
 {
    CheckDirectory("path_to_my_mother_directory");
}
    private void CheckDirectory(string targetDirectory)
    {
        MyLog.LogInfo("Check directory", string.Format("Checking for files in {0} directory", targetDirectory));
        var fileEntries = Directory.GetFiles(targetDirectory);
        foreach (var fileName in fileEntries)
            ProcessFile(fileName);
        // Check subfolders
        var subdirectoryEntries = Directory.GetDirectories(targetDirectory);
        foreach (var subdirectory in subdirectoryEntries)
            CheckDirectory(subdirectory);
    }
    private void ProcessFile(string path)
    {
        MyLog.LogInfo("File Found", string.Format("File '{0}' found", path));
        var Fileinfo = new FileInfo(path);
        if (Fileinfo.Exists && extentionFilesType.Contains(Fileinfo.Extension))
        {
            MyLog.LogInfo("Check extension file", string.Format("File has a searched extension ({0})", Fileinfo.Extension));
            FilesToInsert.Add(Fileinfo);
        }
        else
        {
            MyLog.LogInfo("Check extension file", "File doesn't has a searched extension");
        }
    }

CCD_ 1是一个具有研究扩展的列表。