A Day in the Life of a Developer
Build an Image Display Web Form
By Doug Seven
This week I was asked to build a Web form to display image thumbnails from a directory within a Web application. I needed to link each thumbnail to a full-size image, and as the files in the directory change, the Web form would reflect these changes without any database access. In other words, this Web form had to be a live file-system viewer only for images with related thumbnails. I accomplished this using classes in the System.Drawing and System.IO namespaces.
To begin, created a Web form that uses a DataList to render the thumbnails. In the ItemTemplate of the DataList, created a link tag with the image and image name, which links to the full-size image:
<a href='images/<%# RemoveText( (String)DataBinder.Eval
( Container.DataItem, "Name" ), "thumb_" ) %>'>
<img src='images/<%# DataBinder.Eval
( Container.DataItem, "Name" ) %>' border='0' />
This code uses a helper method named RemoveText. This method takes in the original text and the substring to remove from it; it returns the original text without the substring:
public String RemoveText(String orginalText,
String textToRemove )
return orginalText.Replace(textToRemove, "");
In the Page_Load event handler, you use the System.IO.DirectoryInfo and FileInfo classes to build a bindable array of files:
private void Page_Load(object sender, System.EventArgs e)
String _path = Server.MapPath("images/");
if ( !_path.EndsWith(@"\") )
_path += @"\";
DirectoryInfo _di = new DirectoryInfo(_path);
FileInfo _fi = _di.GetFiles("thumb_*.jpg");
DataList1.DataSource = _fi;
Now create a new DirectoryInfo object using the Web application's path to the images directory. Using the DirectoryInfo.GetFiles method, you return an array of FileInfo objects for files matching "thumb_*.jpg" - this displays all the thumbnails in the directory. If a file is added to or removed from the directory, the Web form will reflect this change on the next request.
The code for the Image Display, available in C#, and five sample jpeg images are available for download.
As a co-founder of http://www.DotNetJunkies.com, a content-based online training resource for .NET developers, Doug Seven has been building applications with the .NET Framework since summer 2000. Seven has co-authored five books related to the .NET Framework: Programming Data-Driven Web Applications with ASP.NET (Sams), ASP.NET: Tips, Tutorials & Code (Sams), Professional ADO.NET (Wrox), Developing Custom Controls for ASP.NET (Sams), and ASP.NET Security (Wrox). Seven's professional .NET consulting clients include Microsoft, the Massachusetts Institute of Technology (MIT), and Tricordia LLC, and the work he has been involved in has included both C# and Visual Basic .NET, Web applications, mobile device applications, XML Web Services, Windows Forms development, and console and service applications. E-mail Doug at mailto:[email protected].