获取所有文件夹直到最后一级

时间:2012-11-27 14:04:09

标签: asp.net asp.net-mvc io asp.net-mvc-4 directory

我想从根目录中检索所有子目录,直到最后一级。

我已经调整了我的代码,但它只检索了第一级文件夹及其中的文件。

有没有办法一直走到最后一层?

这是代码

    Response.Write("<ul class=\"jqueryFileTree\" style=\"display: none;\">\n");

    foreach (DriveInfo drive in allDrives)
    {
        if (drive.IsReady == true) 
        {
            Response.Write("\t<li class=\"drive collapsed\"><a href=\"#\" rel=\"" + drive.ToString() + "\">" + drive.ToString() + "</a>\n");     

            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(drive.ToString());
            Response.Write("<ul>");

            foreach (System.IO.DirectoryInfo di_child in di.GetDirectories())
            {
                Response.Write("\t<li class=\"directory collapsed\"><a href=\"#\" rel=\"" + drive + di_child.Name + "/\">" + di_child.Name + "</a>\n");
                Response.Write("<ul>");

                foreach (System.IO.FileInfo fi in di.GetFiles())
                {
                    string ext = "";

                    if (fi.Extension.Length > 1)
                    {
                        ext = fi.Extension.Substring(1).ToLower();
                    }

                    Response.Write("\t<li class=\"file ext_" + ext + "\"><a href=\"#\" rel=\"" + drive + fi.Name + "\">" + fi.Name + "</a></li>\n");
                }

                Response.Write("</ul></li>");
            }
            Response.Write("</ul></li>");
       }
    }

    Response.Write("</ul>");
}
catch (Exception)
{
    throw;
}

1 个答案:

答案 0 :(得分:3)

你需要一个递归函数。

private IEnumerable<dynamic> GetFilesByDirectory(string path)
{
    var directories = Directory.GetDirectories(path);
    var files = Directory.GetFiles(path);

    yield return new {path, directories, files };

    foreach(var directory in directories)
    {
        yield return GetFilesByDirectory(directory);
    }
}

并作为旁注。你不应该在控制器动作中调用Response.Write。相反,您可以返回ActionResult来渲染视图并将html模板放在视图中。