wpf C#显示选定文件夹中的所有文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12973813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 05:50:08  来源:igfitidea点击:

C# display all files from selected folder

c#wpffileinfodirectoryinfo

提问by omkar patade

I want to display all the files from a selected folder.. ie files from that folder and files from the subfolders which are in that selected folder.

我想显示选定文件夹中的所有文件.. 即来自该文件夹的文件和来自该选定文件夹中子文件夹的文件。

example -

例子 -

I have selected D:\Eg. Now I have some txt and pdf files in that. Also I have subfolders in that which also contain some pdf files. Now I want to display all those files in a data grid.

我选择了 D:\Eg。现在我有一些 txt 和 pdf 文件。此外,我还有一些子文件夹,其中还包含一些 pdf 文件。现在我想在数据网格中显示所有这些文件。

My code is

我的代码是

public void  selectfolders(string filename)
{      
     FileInfo_Class fclass;
     dirInfo = new DirectoryInfo(filename);

     FileInfo[] info = dirInfo.GetFiles("*.*");
     foreach (FileInfo f in info)
     {

        fclass = new FileInfo_Class();
        fclass.Name = f.Name;
        fclass.length = Convert.ToUInt32(f.Length);
        fclass.DirectoryName = f.DirectoryName;
        fclass.FullName = f.FullName;
        fclass.Extension = f.Extension;

        obcinfo.Add(fclass);  
     }
     dataGrid1.DataContext = obcinfo;
} 

What to do now?

现在做什么?

回答by Rawling

Just use

只需使用

FileInfo[] info = dirInfo.GetFiles("*.*", SearchOption.AllDirectories);

which will handle the recursion for you.

它将为您处理递归。

回答by Dmitry Dovgopoly

You should recursivelyselect files from all subfolders.

您应该递归地从所有子文件夹中选择文件。

public void  selectfolders(string filename)
{
    FileInfo_Class fclass;
    DirectoryInfo dirInfo = new DirectoryInfo(filename);

    FileInfo[] info = dirInfo.GetFiles("*.*");
    foreach (FileInfo f in info)
    {
        fclass = new FileInfo_Class();
        fclass.Name = f.Name;
        fclass.length = Convert.ToUInt32(f.Length);
        fclass.DirectoryName = f.DirectoryName;
        fclass.FullName = f.FullName;
        fclass.Extension = f.Extension;
        obcinfo.Add(fclass);
    }
    DirectoryInfo[] subDirectories = dirInfo.GetDirectories();
    foreach(DirectoryInfo directory in subDirectories)
    {
        selectfolders(directory.FullName);
    }
}