I’m making a C# image gallery for a website (I know there’s many free ones out there, but I want the experience). I’m grabbing files from a directory on the website by storing them in a array.
protected void Page_Load(object sender, EventArgs e)
{
string[] files = null;
files = Directory.GetFiles(Server.MapPath(@"Pictures"),"*.jpg");
I then am creating an array of Imagebuttons (which I will use as thumb-nails) and I’m dynamically adding them into a panel on the web form. However, the image buttons are added on the form correctly, but the pictures show the little square/circle/triangle symbol and fail to load the actual image.
ImageButton[] arrIbs = new ImageButton[files.Length – 1];
for (int i = 0; i < files.Length-1; i++)
{
arrIbs[i] = new ImageButton();
arrIbs[i].ID = "imgbtn" + Convert.ToString(i);
arrIbs[i].ImageUrl = Convert.ToString(files[i]);
Response.Write(Convert.ToString(files[i]) + "**--**");
arrIbs[i].Width = 160;
arrIbs[i].Height = 100;
arrIbs[i].BorderStyle = BorderStyle.Inset;
//arrIbs[i].BorderStyle = 2;
arrIbs[i].AlternateText = System.IO.Path.GetFileName(Convert.ToString(files[i]));
arrIbs[i].PostBackUrl = "default.aspx?Img=" + Convert.ToString(files[i]);
pnlThumbs.Controls.Add(arrIbs[i]);
}
}
This may or may not be related to the issue (if not related, it is a sub-question). When setting the Server.MapPath() to @”~/Gallery/Pictures” (which is where the directory is in relevance to the site root) I get an error. It states that “C:/…/…/…/… could not be found” The web-site only builds if I set the directory as “Pictures”, which is where the pictures are, and “Pictures” is in the same folder as “Default.aspx” which the above code is at. I never have much luck with the ~ (tilda) character. Is this a file-structure issue, or a IIS issue?
The problem with this is that you’re setting a path on the server as the image button source. The browser will try to load these images from the client’s machine, hence they cannot load. You will also need to make sure that the ASPNET user on the server has permissions to that folder.
What you need to do is to serve the jpeg’s streams as the source for the image buttons.
You could have an aspx page which takes in the path in a query string parameter and loads the file and serves it.
Eg, have a page called GetImage.aspx as such:
and now when you create your ImageButtons, this should be your ImageUrl: