0

I am developing a Asp.Net MVC 4 application using VS 2012. The application when running in local is using the IIS Express as web server.I am facing issues in trying to access a file which is part of my solution. I have the following action method :

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

            return File(imageByte, contentType);
        }

In the first line, I am getting the following error :

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

I know that the above path is not correct but I am not able to understand what path I should provide in order to solve this problem.

Regards Pawan Mishra

Charles
  • 50,943
  • 13
  • 104
  • 142
Pawan Mishra
  • 7,212
  • 5
  • 29
  • 39

1 Answers1

10

You can use Server.MapPath() to get the actual directory like this:

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

Some people advocate using HostingEnvironment.MapPath() instead: What is the difference between Server.MapPath and HostingEnvironment.MapPath?

Community
  • 1
  • 1
Andrew Morton
  • 24,203
  • 9
  • 60
  • 84