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.

2 comments:
great artice. really this is an informative post . thanks for sharing
Web Development Vancouver
Hi,Becoming a successful web designer requires more than a good aesthetic and Photoshop skills. Being good at design simply is no longer good enough to make it in the modern, competitive world of Web Design Cochin. Here are a few tips that budding web designers should keep in mind when building their burgeoning careers. Thanks..
Post a Comment