Introduction
Here, we don't want to include the img
tag and then include src
to show images on our WebPage. All this is done by code-behind.
So how will it be useful. Here are the advantages.
Suppose you have made a page for a client in which images are shown of his/her company and after some period of time, your client gives you a call saying that they have some new pictures and you should just upload them too. Now what? You have to first get those images and put them in the online folder of that client website and then take that page do some edit and update that page.
By using the code below, we can add dynamically, just add the new images or replace the old one in your Images Folder/Directory, that's all and the web page will automatically add/update them.
Background
You need to have a little bit knowledge of:
using System.IO;
using System.Web;
Using the Code
Here we are getting all the Images/files from our directory from code-behind by using:
Directory.GetDirectories Method (Path, SearchPattern, SearchOption)
path
- Here path is the folder/directory where your files/Images are located.
*(searchPattern)
- searchPattern
can be a combination of literal and wildcard characters, but doesn't support regular expressions.
Example: If we want only png files, then we will use as - *.png or if we only want jpeg then - *.jpeg
SearchOption
- One of the enumeration values that specifies whether the search operation should include all subdirectories or only the current directory.
TopDirectoryOnly
- Includes only the current directory in a search operation.AllDirectories
- Includes the current directory and all its subdirectories in a search operation. This option includes reparse points such as mounted drives and symbolic links in the search.
string imagepath = Server.MapPath("~/Slider/Images/");
string[] images =Directory.GetFiles(imagepath,"*",SearchOption.TopDirectoryOnly);
foreach (string filepath in images)
{
Image te = new Image();
string fileurl = Path.GetFileName(filepath.ToString());
te.ToolTip = fileurl;
te.ImageUrl = "~/Slider/Images/" + fileurl;
te.Height = 100;
te.Width = 200;
te.CssClass = "zoom";
myimages.Controls.Add(te);
}
You can access your div
by adding runat=server
in it.
For example:
<div id="your_div_name" runat="server"></div>
That's all. Use the code and save time.