tags:

views:

50

answers:

2

I have a folder C:\Images which has a some images. This folder is not inside my project and I would to know if there is a way to load an image from that folder on to an ASP.NET Image control.

<asp:Image ID="img" runat="server" />

One solution could be to make the Images folder a Virtual directory on the IIS but I would like to know if this can be done without creating a virtual directory for the Images folder.

+1  A: 

At the end of the day, the image needs to be sitting somewhere that the user's browser can see it.

That means your options are:

  • Move the image to a directory on the webserver
  • Set the image's directory up as a Virtual Directory
  • Copy the image at runtime to a directory on the webserver

The Best Practice answer is to put the images into your project if they're part of the site, or to map a Virtual Directory if the directory is a store of user-uploaded images.

Jason Kester
+2  A: 

Assuming proper access is granted to the Images folder you could do something like this:

Your main page:

protected void Page_Load(object sender, EventArgs e)
{
    mainImage.ImageUrl = "ImageHandler.ashx?image=MyImage.jpg";
}

ImageHandler:

public void ProcessRequest(HttpContext context)
{
    byte[] imageBytes = File.ReadAllBytes(@"C:\Images" + context.Request["image"]);
    context.Response.ContentType = "image/jpeg";
    context.Response.BinaryWrite(imageBytes);
}
Matt Dearing
Well described, but you forgot to disclaim in all caps that he should NEVER DO THAT UNLESS HE HAS A VERY GOOD REASON, going on to explain how inefficient it is compared to, say, serving the file from the webserver. If he's restricting those images to only certain users, then yes, this is one way to do it. For pretty much any other reason, it's a terrible idea, though as you describe, it's technically possible.
Jason Kester
I actually thought about that, but I was just answering his question that it is possible. I agree with all of your points and am not really sure why he can't just add this image to his web project. Thank you for the comment.
Matt Dearing