asp.net-mvc 获取文件夹中的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2039910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:01:58  来源:igfitidea点击:

Get files in a folder

asp.net-mvcfile

提问by griegs

In my MVC application I have the following paths;

在我的 MVC 应用程序中,我有以下路径;

  • /content/images/full
  • /content/images/thumbs
  • /内容/图像/完整
  • /内容/图像/拇指

How would I, in my c# controller, get a list of all the files within my thumbs folder?

我如何在我的 c# 控制器中获取我的拇指文件夹中所有文件的列表?

Edit

编辑

Is Server.MapPath still the best way?

Server.MapPath 仍然是最好的方法吗?

I have this now DirectoryInfo di = new DirectoryInfo(Server.MapPath("/content/images/thumbs") );but feel it's not the right way.

我现在有这个,DirectoryInfo di = new DirectoryInfo(Server.MapPath("/content/images/thumbs") );但觉得这不是正确的方法。

is there a best practice in MVC for this or is the above still correct?

MVC 中是否有最佳实践,或者以上仍然正确?

采纳答案by Daniel T.

Directory.GetFiles("/content/images/thumbs")

That will get all the files in a directory into a string array.

这会将目录中的所有文件放入一个字符串数组中。

回答by slfan

.NET 4.0 has got a more efficient method for this:

.NET 4.0 为此提供了一种更有效的方法:

Directory.EnumerateFiles(Server.MapPath("~/Content/images/thumbs"));

You get an IEnumerable<string>on which you can iterate on the view:

你会得到一个IEnumerable<string>你可以在视图上迭代的:

@model IEnumerable<string>
<ul>
    @foreach (var fullPath in Model)
    {
        var fileName = Path.GetFileName(fullPath);
        <li>@fileName</li>
    }
</ul>