Reputation: 2308
I want to retreive all sub directories from a root directory until the last level.
I have ajusted my code but it only retrieve first level folders and the files inside it.
Is there a way to go all the way through the last level?
This is the code
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;
}
Upvotes: 0
Views: 119
Reputation: 7591
you need a recursive function.
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);
}
}
and as a side note. you should not be calling Response.Write within the controller action. instead you can return an ActionResult
for rendering a view and put your html template in the view.
Upvotes: 3