【问题标题】:How to load images to page from image folder dynamically如何将图像从图像文件夹动态加载到页面
【发布时间】:2014-03-15 23:19:06
【问题描述】:

我正在使用 MVC4 c#。我正在尝试通过读取图像文件夹的内容并执行 foreach 循环来动态加载需要在页面上显示的图像。我不确定如何读取位于项目中的名为 ImageFiles 的文件夹的内容,而不是服务器的 c:\。这是我使用的,它可以在我的本地计算机上运行,​​但是当我使用 ../../filename/filename/ImageFiles 作为路径时它不起作用。有人可以帮忙吗?

string filePath = @"../../Content/EventFiles/ImageFiles";
DirectoryInfo directory = new DirectoryInfo(filePath);

@foreach (FileInfo file in directory.GetFiles())
{
    <\a href="../../Content/EventFiles/ImageFiles/@file.Name">
       <\img src="/Content/EventFiles/ImageFiles/@file.Name" />
    <\/a>
}

【问题讨论】:

  • 我不知道这在任何环境中对你有什么作用,但你会想看看Server.MapPath()
  • 一种策略是确定图像的文件系统路径,并将其与网站根目录的文件系统路径进行比较以进行解析。一旦我进入 System.IO 命名空间,我发现这样做会更容易。但我应该在我最初的评论中更充分地解释这一点。

标签: asp.net asp.net-mvc asp.net-mvc-4 c#-4.0


【解决方案1】:

您没有正确引用文件路径。
在你的视图上试试这个..

@{DirectoryInfo dir = new DirectoryInfo(Server.MapPath(Url.Content("~/Content/EventFiles/ImageFiles")));}
@foreach (var file in dir.GetFiles())
{
    <img src="@Url.Content("~/Content/EventFiles/ImageFiles/" + file.Name)" />
}

【讨论】:

    【解决方案2】:

    答案是 Server.MapPath()。对于桌面应用程序 DirectoryInfo() 有效,但对于 Web 应用程序,我必须使用 Server.MapPath()。

    谢谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-01
      • 2012-05-01
      • 2021-01-02
      • 2020-10-08
      • 1970-01-01
      • 2011-11-15
      相关资源
      最近更新 更多