Main Logo
homelink tutorialslink softwarelink comicslink aboutlink contactlink

Tutorial: How to Implement Autoversioning with ASP.NET Master Pages


Example Master Page Markup
<head>
    <title>Your Website Title</title>
    <link rel="stylesheet" type="text/css" href="<% =auto_version("CSS/myStyle.css") %>" />
    <script type="text/javascript" language="javascript" src="<% =auto_version("js/myScript.js") %>"></script>
</head>
    
Code Behind Dependencies
using System.IO;
    
Master Page Code Behind
//appends a version number to the end of css and js files
protected string auto_version(string filename)
{
    //check if file exists
    string filepath = Server.MapPath("~/" + filename);
    if(!File.Exists( filepath ))
    {
        return filename + "?ver=noexist";
    }

    //get last modified date of file to use as version number
    DateTime madetime = File.GetLastWriteTime(filepath);
    string mtime = madetime.Month.ToString() + madetime.Day.ToString() + madetime.Year.ToString();

    //make filename relative to root directory
    filename = "/" + filename;

    //append version number to end of filename
    if (filepath.EndsWith(".css"))
    {
        return filename.Replace(".css", ".css?ver=" + mtime);
    }
    else if (filepath.EndsWith(".js"))
    {
        return filename.Replace(".js", ".js?ver=" + mtime);
    }
    else
    {
        return filename;
    }
}
    

Published: September 17, 2011


Author's Note: CSS and JS file paths in the Master Page markup head section must be relative to the root directory without using a leading "/", "../", etc.