返回给定路径中所有子目录的类型

时间:2013-10-04 04:25:29

标签: c# asp.net-mvc-4

我正在使用c#进行我的mvc4项目。我试图获取目录中的所有子目录。并在我的视图中列出它

为此我正在编写以下代码

控制器

public ActionResult Gallery()
    {
        string folderpath = Server.MapPath("~/Content/Gallery/GalleryImages");
        List<string> currentimage = new Gallery().GetGalleryName(folderpath);
        //What will be the return type???/
        return View(currentimage);
    }

模型

public List<string> GetGalleryName(string path)
    {
        DirectoryInfo di = new DirectoryInfo(path);
        DirectoryInfo[] subdir = di.GetDirectories();
        List<String> files = new List<String>();
        foreach (DirectoryInfo dir in subdir)
        {
            var name = dir.Name;
            files.Add(name);
        }

        return files;
    }

我的代码是对的吗?那么控制器和模型中的返回类型是什么?请帮帮我

3 个答案:

答案 0 :(得分:1)

将控制器中的foreach循环更改为

foreach (DirectoryInfo dir in subdir)
        {
            files.Add(dir.Name);
        }

并从

更改您的控制器
public ActionResult Gallery()
    {
        string folderpath = Server.MapPath("~/Content/Gallery/GalleryImages");
        string[] currentimage = new Gallery().GetGalleryName(folderpath);
        //What will be the return type???/
        return View(currentimage);
    }

public ActionResult Gallery()
    {
        string folderpath = Server.MapPath("~/Content/Gallery/GalleryImages");
        List<String> currentimage = new Gallery().GetGalleryName(folderpath);
        //What will be the return type???/
        return View(currentimage);
    }

我没试过,但这应该有效。希望它有所帮助

答案 1 :(得分:1)

将foreach循环更改为

 foreach (DirectoryInfo dir in subdir)
    {
                    files.Add(dir.FullName);
    }

答案 2 :(得分:0)

在你的控制器中试试这个

public ActionResult Gallery()
{
  List<String> galleryList = new List<String>();
  string folderpath = Server.MapPath("~/Content/Gallery/GalleryImages");
  string[] currentimage = new Gallery().GetGalleryName(folderpath);
  foreach (var folder in currentimage) {
    galleryList.Add(folder);
  }
return View(galleryList);
}