Read all files in directory sub folders

若如初见. 提交于 2019-12-22 10:21:37

问题


I have a folder - "C:\scripts"

Within "scripts" I have several sub folders e.g. - "C:\scripts\subfolder1" "C:\scripts\subfolder2" etc, that contain html files.

I am trying to use the following code -

 foreach (string file in Directory.EnumerateFiles(@"C:\scripts","*.html"))
        {
            string contents = File.ReadAllText(file);
        }

However this does not work due to the html files being in the sub folders.

How can I access the html files in the sub folders without having to manually put in the path of each sub folder?


回答1:


use this overload from DirectoryInfo

var dir = new DirectoryInfo(@"c:\scripts");
foreach(var file in dir.EnumerateFiles("*.html",SearchOption.AllDirectories))
{

}



回答2:


Directory.EnumerateFiles(@"C:\scripts","*.html",SearchOption.AllDirectories)

Seems to be the right solution for me try it :)




回答3:


Maybe this works?

foreach (string file in Directory.GetFiles("C:\\Scripts\\", "*.html", SearchOption.AllDirectories))
{
    string contents = File.ReadAllText(file);
}



回答4:


From SearchOption.AllDirectories

Includes the current directory and all its subdirectories in a search operation. This option includes reparse points such as mounted drives and symbolic links in the search.

Try like this;

var d = new DirectoryInfo(@"c:\scripts");
foreach(var fin d.EnumerateFiles("*.html", SearchOption.AllDirectories))
{

}


来源:https://stackoverflow.com/questions/15363478/read-all-files-in-directory-sub-folders

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!