2012-11-27 64 views
0

我想從根目錄中檢索所有子目錄直到最後一級。獲取所有文件夾,直到最後一級

我調整了我的代碼,但它只檢索第一級文件夾和其中的文件。

有沒有辦法一路走過最後一級?

這是代碼

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; 
} 

回答

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模板放入視圖中。

相關問題