0

我正在使用 VS 2012 开发 Asp.Net MVC 4 应用程序。该应用程序在本地运行时使用 IIS Express 作为 Web 服务器。我在尝试访问作为我的解决方案一部分的文件时遇到问题。我有以下操作方法:

public FileContentResult GetImage()
        {
            byte[] imageByte = System.IO.File.ReadAllBytes(@"/MyPics/My.jpg");
            string contentType = "image/jpeg";

            return File(imageByte, contentType);
        }

在第一行,我收到以下错误:

Could not find a part of the path 'C:\Program Files (x86)\IIS Express\~\MyPics\My.jpg'

我知道上面的路径不正确,但我无法理解我应该提供什么路径来解决这个问题。

问候帕万米什拉

4

1 回答 1

10

您可以使用 Server.MapPath() 来获取实际目录,如下所示:

byte[] imageByte = System.IO.File.ReadAllBytes(Server.MapPath("~/MyPics/My.jpg"));

有人提倡使用 HostingEnvironment.MapPath() 代替:Server.MapPath 和 HostingEnvironment.MapPath 有什么区别?

于 2013-04-07T15:26:01.790 回答