Dotnet Core:显示多个按名称过滤的图像文件

时间:2019-12-28 10:29:02

标签: c# image file asp.net-core .net-core

假设我要在“剃刀”视图中显示几个图像。我要显示的图像数量取决于满足特定条件的图像数量,例如该文件夹中有多少文件名以{id}开头,例如~/img/solutions/{year}/{variant}/{id}.png~/img/solutions/{year}/{variant}/{id}-1.png

算法将是查看该文件夹,检查文件,选择满足某些命名条件的文件,选择相对路径,然后将其放入一个集合中,我可以在视图中简单地进行查找。我该如何实现?

编辑:根据Rajesh G的建议,我将添加到目前为止的内容

    private readonly IWebHostEnvironment _hostingEnvironment;

    public IActionResult Index()
    {
        // Variables for a simple example
        var year = 17;
        var variant = 1;
        var id = 1;

        var webRoot = _hostingEnvironment.WebRootPath;
        var appData = Path.Combine(webRoot, $"img/solutions/{year}/{variant}/{id}.png");

        var model = Directory.EnumerateFiles(appData).Select(x => Url.Content(x));

        return View(model);
    }

此代码有效,尽管传递给视图的字符串尚未修剪为相对路径。它只会选择名称正确的文件。我想更改该代码,以便如果该目录中有{id}.png{id}-1.png{id}-2.png,则它们不仅可以使用。

在以下行中使用{id}*.png{id}*会使应用抛出异常。

var appData = Path.Combine(webRoot, $"img/solutions/{year}/{variant}/{id}*.png");

1 个答案:

答案 0 :(得分:0)

好的,我想出了一种对我有用的方法。

无论好坏,我都改变了逻辑–我没有从{id}*.*中选择~/img/solutions/{year}/{variant}/,而是为它们创建了一个新文件夹,然后选择~/img/solutions/{year}/{variant}/{id}/中的所有内容,因为这是我唯一的方法使它工作。

        private readonly IWebHostEnvironment _hostingEnvironment;

        public IActionResult Index()
        {
            var year = 17;
            var variant = 1;
            var id = 1;

            var webRoot = _hostingEnvironment.WebRootPath;
            var relativePath = $"/img/solutions/{year}/{variant}/{id}/";
            var fullPath = Path.Combine(webRoot, $"img/solutions/{year}/{variant}/{id}");

            var model = Directory.EnumerateFiles(fullPath)
                             .Select(file => relativePath + Path.GetFileName(file));

            return View(model);
        }