我是 MVC 的新手,我的问题是我没有以正确的方式解决这个问题,它目前按我的预期工作,但我不确定结构和方法的放置位置。
我有一个用于帮助显示到视图(视图模型?)的类FolderFileList
,它还包含一个名为 的函数GetFolderStructure()
,该函数采用路径和文件夹并循环创建所有文件和文件夹的列表,然后返回它们。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
namespace xxx.Models
{
public class FolderFileList
{
public DirectoryInfo Directory { get; set; }
public FileInfo File { get; set; }
public List<FileInfo> FileList { get; set; }
public List<DirectoryInfo> FolderList { get; set; }
public List<DirectoryInfo> RootFolderList { get; set; }
public string FolderRoot { get; set;
}
public static FolderFileList GetFolderStructure(string path, string foldername)
{
//initialise variables
DirectoryInfo selecteddirectory = null;
DirectoryInfo rootdirectory = null;
var files = new List<FileInfo>();
var listoffilesandfolders = new FolderFileList();
listoffilesandfolders.FileList = new List<FileInfo>();
listoffilesandfolders.FolderList = new List<DirectoryInfo>();
listoffilesandfolders.RootFolderList = new List<DirectoryInfo>();
listoffilesandfolders.FolderRoot = foldername;
//get selected directory
try
{
selecteddirectory = new DirectoryInfo(path + foldername);
listoffilesandfolders.FolderList = selecteddirectory.GetDirectories("*", SearchOption.AllDirectories).ToList();
}
catch (DirectoryNotFoundException exp)
{
throw new Exception("Could not open the directory", exp);
}
catch (IOException exp)
{
throw new Exception("Failed to access directory", exp);
}
//get root directory
try
{
rootdirectory = new DirectoryInfo(path);
listoffilesandfolders.RootFolderList = rootdirectory.GetDirectories("*", SearchOption.TopDirectoryOnly).ToList();
}
catch (DirectoryNotFoundException exp)
{
throw new Exception("Could not open the directory", exp);
}
catch (IOException exp)
{
throw new Exception("Failed to access directory", exp);
}
//get all files and subfolder files
try
{
files = selecteddirectory.GetFiles("*", SearchOption.AllDirectories).ToList();
}
catch (FileNotFoundException exp)
{
throw new Exception("Could not find file", exp);
}
catch (IOException exp)
{
throw new Exception("Failed to access fie", exp);
}
files = files.OrderBy(f => f.Name).ToList();
foreach (FileInfo file in files)
{
listoffilesandfolders.FileList.Add(file);
}
return listoffilesandfolders;
}
}
我的控制器:
public ActionResult Folder(string foldername)
{
var path = Server.MapPath(@"~\");
var folderstructure = FolderFileList.GetFolderStructure(path, foldername);
return View(folderstructure);
}
我的问题是:
- 我把这门课放在哪里?它当前位于模型文件夹中。
- 方法依赖于类,在类中可以吗?我该怎么办?