109*_*793 4 .net c# asp.net-mvc view
我想要做的是在我的MVC应用程序的View中显示位于我的服务器上的文件夹的内容.
我有我认为应该采取的措施,但是我有点不确定如何实施相应的视图,我想知道是否有人可以指出正确的方向.(而且,如果有人认为我的行动可以改进,欢迎提出建议:))
这是行动:
public ActionResult Index()
{
DirectoryInfo salesFTPDirectory = null;
FileInfo[] files = null;
try
{
string salesFTPPath = "E:/ftproot/sales";
salesFTPDirectory = new DirectoryInfo(salesFTPPath);
files = salesFTPDirectory.GetFiles();
}
catch (DirectoryNotFoundException exp)
{
throw new FTPSalesFileProcessingException("Could not open the ftp directory", exp);
}
catch (IOException exp)
{
throw new FTPSalesFileProcessingException("Failed to access directory", exp);
}
files = files.OrderBy(f => f.Name).ToArray();
var salesFiles = files.Where(f => f.Extension == ".xls" || f.Extension == ".xml");
return View(salesFiles);
}
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激,谢谢:)
FileInfo对象,还是仅检索文件路径?如果后者为真,则只返回IEnumerable<string>视图(而不是a IEnumerable<FileInfo>,这是您在上面的代码中所做的).提示:只需添加Select对Linq表达式的调用...如果您只需要文件名,则可以将Linq查询更改为
files = files.Where(f => f.Extension == ".xls" || f.Extension == ".xml")
.OrderBy(f => f.Name)
.Select(f => f.Name)
.ToArray();
return View(files);
Run Code Online (Sandbox Code Playgroud)
然后(假设默认项目模板)将以下内容添加到Index.cshtml视图中
<ul>
@foreach (var name in Model) {
<li>@name</li>
}
</ul>
Run Code Online (Sandbox Code Playgroud)
这将显示文件名列表