Monday, February 1, 2010

Where's My File? Server.MapPath to the Rescue!

During the task of trying to serve up dynamic image content from a database, it turned out that in certain circumstances I also needed to read a local image file on the server too.

This was for the case in which no data was found or was missing for some reason -- basically an "Image Not Found" image. The problem is that I had not had to deal with the problem of locating a file in the web application file hierarchy before, strangely enough.

So when I tried to use the File.OpenRead() method, each of the various values for the path I tried didn't work properly and the file could not be found.

Thankfully, I found this post on the ASP.NET forums:

How to read image file ? - ASP.NET Forums

The important piece of information for me was the bit about using Server.MapPath() -- that was the crucial piece of the puzzle I was missing.

So here is what I came up with:

protected byte[] GetImageFromFile(string fileName)
{
byte[] image = new byte[1];
image[0] = 0;

try
{
string filePath =
Server.MapPath("~/images/" + fileName);

if (File.Exists(filePath))
{
FileStream fs = File.OpenRead(filePath);
image = new byte[fs.Length];
fs.Read(image, 0, image.Length);
}

}
catch (Exception ex)
{
logger.Error(ex);
}

return image;
}


Then I call this method and write it out with Response.BinaryWrite() (shouts out to Derek Pinkerton as well for his good blog post on the subject of Response.BinaryWrite() - it was very helpful in this process as well...)

I could genericize it to retrieve a file from anywhere, for now I YAGNI'ed it since I really was just needing to serve up image files from the image directory. If that changes in the future I can very easily modify it or create a more general method for handling that. A trivial modification.