MVC displays files from a folder in a view

What I want to do is display the contents of a folder that is on my server in a view in my MVC application.

I have something that, it seems to me, 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 anyone could point in the right direction. (and also, if someone thinks that my action could be improved, advice would be welcome :))

Here is the action:

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 :)

+4
source share
3 answers

If you only need file names, 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); 

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

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

A list of file names will be displayed.

+5
source
  • IMHO you should expose only what is really necessary for presentation. Think about it: do you really need to get the whole FileInfo object or just the file path? If the latter is true, just return the IEnumerable<string> to the view (instead of IEnumerable<FileInfo> , what do you do in the above code). Hint: just add a Select call to your Linq expression ...
  • Then your view will simply display this model - for this you need a foreach loop and some HTML code.
+5
source

This is a simplified example of the appearance of a razor. It will call the names of your files in the HTML table.

  @model IEnumerable<FileInfo> <h1>Files</h1> <table> @foreach (var item in Model) { <tr> <td> @item.Name </td> </tr> } </table> 
+3
source

Source: https://habr.com/ru/post/1340191/


All Articles