【问题标题】:VS 2012 & IIS Express. Could not find a part of the path 'C:\Program Files (x86)\IIS Express\~\MyPics\My.jpg'VS 2012 和 IIS Express。找不到路径“C:\Program Files (x86)\IIS Express\~\MyPics\My.jpg”的一部分
【发布时间】:2013-04-07 14:53:23
【问题描述】:

我正在使用 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'

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

问候 帕万·米什拉

【问题讨论】:

    标签: c# visual-studio-2012 iis-express


    【解决方案1】:

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

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

    有些人提倡使用 HostingEnvironment.MapPath() 代替:What is the difference between Server.MapPath and HostingEnvironment.MapPath?

    【讨论】:

    • 太棒了,到处找这个。谢谢!
    • 这个方法不错,不得不提一下:HttpContext.Current.Server.MapPath
    • @SharifYazdian 此外,您可以将当前上下文作为参数传递给,例如,HttpContext.Current 不可用的单独类中的共享方法,并使用context.Server.MapPath(...)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 2014-05-10
    • 2016-12-19
    • 1970-01-01
    • 2020-02-07
    相关资源
    最近更新 更多