This user control (.ascx) will display the latest image found in a folder of your choosing. We use it to display the latest image from our web cam.

There are two properties you can set when using the control, ImgFolder and ImgFileExt. Use the control by adding this to any existing .aspx page:


<%@ Register TagPrefix="uc1" TagName="LatestImageControl" src="LatestImageControl.ascx" %>

... YOUR NORMAL HTML GOES HERE ...

<uc1:LatestImageControl ImgFolder="\images\webcam" ImgFileExt=".jpg" id="LatestImageControl1" runat="server"></uc1:LatestImageControl>


The control uses only inline code so you don't have to recompile anything to use it.  Don't be afraid of it, just paste it into a file called LatestImageControl.ascx and you're good to go!  You can use it in any page you want as shown above.

File LatestImageControl.ascx:


<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Collections" %>
<%@ Import Namespace="System.IO" %>
<%@ Control Language="C#" ClassName="LatestImageControl" %>

<script runat="server">
    private string _imgVirtualFolder = "/images"; // default
    public string ImgFolder
    {
        get{ return _imgVirtualFolder; }
        set{ _imgVirtualFolder = value; }
    }
    
    private string _imgFileExt = ".jpg"; // default
    public string ImgFileExt
    {
        get{ return _imgFileExt; }
        set{ _imgFileExt = value; }
    }
    
    protected override void OnLoad(EventArgs e)
    {
        Response.Cache.SetNoStore();
        base.OnLoad(e);
        string physFolder = Server.MapPath(_imgVirtualFolder);
        string image = GetLatest(physFolder, _imgFileExt);
        if ( image != null)
        {
            Image1.Visible = true;
            Image1.ImageUrl =  _imgVirtualFolder + "\\" + image;
        }
        else
        {
            Image1.Visible = false;
        }
    }
    public static string GetLatest(string physFolder, string fileExt)
    {
        DirectoryInfo dir = new DirectoryInfo(physFolder);
        FileInfo[] fileInfos = dir.GetFiles( "*" + fileExt );
        SortedList list = new SortedList();        
        foreach ( FileInfo fInfo in fileInfos )
        {
            list.Add( fInfo.LastWriteTime, fInfo.Name );
        }
        return (list.Count == 0) ? null : (string)list.GetByIndex(list.Count-1);
    }
</script>
<asp:Image id="Image1" runat="server"></asp:Image>