【问题标题】:How to get image files in c# using relative path?如何使用相对路径在 c# 中获取图像文件?
【发布时间】:2012-01-20 19:33:15
【问题描述】:

我已经检查了这个线程How to get files in a relative path in C#,该目录在 IDE 中,这对我来说不正确。我有一个网站应用程序,需要从同级文件夹img 获取图像文件。我可以使用以下代码来获取它们:

DirectoryInfo path=new DirectoryInfo(@"c:\WebsiteSolution\wwwroot\Chat\img");
FileInfo[] images = path.GetFiles("*");

但是我想用.\img之类的东西来代替第一行代码中的参数,可以吗?

【问题讨论】:

  • 相对于什么——应用程序的文件夹?

标签: c#


【解决方案1】:

调用 Server.MapPath 实用程序以获取相对路径。

DirectoryInfo path = Server.MapPath("~\Chat\img");

【讨论】:

    【解决方案2】:

    对于 ASP.Net 使用 MapPath - http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath.aspx

    另外,如果你只需要构建渲染页面的路径,只需 /Chat/img/My.gif 就足够了。

    【讨论】:

      【解决方案3】:

      您需要找到一个锚点 - 例如Application.ExecutablePath - 然后使用该锚点和Path.Combine() 来访问您的图像目录。

      如果您的Application.ExecutablePath 是:@"c:\WebSiteSolution\wwwroot\chat\code",那么您可以使用string imgPath = Path.Combine(Application.ExecutablePath, @"..\img");

      如果您很难找到一个好的主播,可以考虑很多。您可以通过Assembly.GetExecutingAssembly().Location获取执行程序集的路径

      【讨论】:

      • 我不会将这种方法用于托管在 IIS 中的 ASP.NET 应用程序。一方面,ExecutablePath 很可能是 Windows 文件夹下的某个可执行文件。另外,我相信 IIS 会制作程序集的影子副本。我不确定这会如何影响 Assembly.Location 属性,但它的值可能不是您所期望的。使用 HttpServerUtility.MapPath 是获取虚拟路径的物理文件路径的标准方法。
      • 感谢您的提示。我在桌面应用程序编程中不得不处理这个问题很多,但我没有做太多的网络编程。
      猜你喜欢
      • 2011-03-16
      • 1970-01-01
      • 2012-04-09
      • 2015-11-08
      • 2017-04-21
      • 2013-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多