spud
spud

Reputation: 251

ASP.NET Image control not displaying an image

I am trying to display an image from "C:\temp". Here's the code:

string root = "C:\temp\";

string[] files = Directory.GetFiles(root);

foreach (string f in files)
{
    if (Path.GetFileName(f).Contains(user.WorkEmail))
    {
        img1.ImageUrl = root + Path.GetFileName(f);
    }
}

If an image is not found, I get a thumbnail with a red "X" - fine, as expected.

If an image is found, I get a thumbnail but no image gets loaded/displayed. When I right click the thumbnail and go 'Properties' it shows the correct filename.

Upvotes: 1

Views: 7548

Answers (3)

icaptan
icaptan

Reputation: 1535

i had that problem and solved it ... you should give the image adres cut e.g:

www.yoursite.com/folder/image.jpg

Your image source should be = "folder/image.jpd" No need of root or website.

Upvotes: 0

Paul
Paul

Reputation: 36349

looks like you're creating strings of the form "C:\temp\myfile.jpg", right?

That's not a valid URL. your address needs to be either relative to your website's root (e.g. /content/myfile.jpg) or else it needs to include the protocol (e.g. file://c:\temp\myfile.jpg for local files or http://mysite.com/content/myfile.jpg for web access)

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039418

You need to make this image part of the web site in order to display it properly. You need to use a relative URL:

img1.ImageUrl = '/App_Data/foo.jpg';

The image file cannot be located anywhere, when it is part of the web site a separate request is made to the server to fetch the image which is served by IIS. If you want to use image files located in a folder outside of your site root you will need to write a generic handler which will read the image contents, stream it to the response with correct content-type and then point the ImageUrl to this handler.

Upvotes: 6

Related Questions