【问题标题】:Dotnet Core: Display Multiple image files filtered by nameDotnet Core:显示按名称过滤的多个图像文件
【发布时间】:2019-12-28 10:29:02
【问题描述】:

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

该算法将查看该文件夹,检查文件,选择满足特定命名条件的文件,选择相对路径,将其放入我可以在视图中简单地 foreach 的集合中。我怎样才能做到这一点?

编辑:正如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");

【问题讨论】:

  • 分享你目前写的代码。

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


【解决方案1】:

好的,我想出了一个适合我的方法。

无论好坏,我都改变了逻辑——我没有从~/img/solutions/{year}/{variant}/ 中选择{id}*.*,而是为这些创建了一个新文件夹并选择~/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);
        }

【讨论】:

    猜你喜欢
    • 2010-10-09
    • 2023-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-18
    • 2022-01-06
    • 2019-06-26
    相关资源
    最近更新 更多