MVC在视图中显示文件夹中的文件 [英] MVC Display Files from a Folder in a View

查看:160
本文介绍了MVC在视图中显示文件夹中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做的是在MVC应用程序的视图"中显示位于服务器上的文件夹的内容.

What I'm looking to do, is display the contents of a folder which is located on my server in a View in my MVC application.

我认为应该为该行动做好准备,但是我不确定如何实现相应的观点,我想知道是否有人可以指出正确的方向. (而且,如果有人认为我的行为可以得到改善,欢迎提出建议:))

I have what I think should be in place for the Action, however I'm a little unsure how to go about implementing the corresponding view and I was wondering if someone could point be in the right direction on that. (and also, if someone thinks my Action could be improved, advice would be welcome :) )

这是动作:

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

任何帮助将不胜感激,谢谢:)

Any help would be appreciated, thanks :)

推荐答案

如果只需要文件名,则可以将Linq查询更改为

If you only want the file names then you can change your Linq query to

files = files.Where(f => f.Extension == ".xls" || f.Extension == ".xml")
  .OrderBy(f => f.Name)
  .Select(f => f.Name)
  .ToArray();
return View(files);

然后(假设使用默认的项目模板)将以下内容添加到Index.cshtml视图

Then (assuming the default project template) add the following to the Index.cshtml view

<ul>
  @foreach (var name in Model) {
    <li>@name</li>
  }
</ul>

将显示文件名列表

这篇关于MVC在视图中显示文件夹中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆