Remove image from Browser Cache when Image changes using Asp.Net C# and Vb.Net

← PrevNext →

Browsers, cache images and other static assets on a website, to reduce upload time and bandwidth. This process helps websites load faster, by extracting contents from the cache (a temporary storage in your computer). However, sometimes you need clear the browser cache, if the websites contents change frequently, such as images. I am sharing a simple trick here, which shows how to load clear browser cache when image changes using Asp.Net C# and Vb.Net.

I was recently updating my Easy Image Resizer tool, and I noticed that every time I select an image for resizing or cropping, the browser shows the previously selected image, instead of the new image. This is the browser’s default behavior. I had to overcome this issue and I figured out that the solution to this problem is simple. It’s a trick rather.

Browsers don’t scan every image (or any content) to check if it’s the same as before. Browser cache works by identifying objects, such as images, by its name.

Since I am using Asp.Net, I can simply change the name of the image at the server side itself, by concatenating the image name with date and time (since its always unique), and send the image (with a new name every time) to the browser.

Here’s how you should do this.

The Markup
<img id="myImage" alt="image" src="" style="border:none;max-width:100%;" runat="server" />
Code in C#
protected void Page_Load(object sender, EventArgs e)
     myImage.Src = "";
     myImage.Src = "~/car.png" + "?" + DateTime.Now.Ticks.ToString();    // Add date time to prevent caching.

Here's how it shows the image name in the browser console window.

Remove image from Browser Cache when image changes using Asp.Net

The code concatenates a new date and time with the image name for every page load, thereby receiving a new source name for the same image.

Note: If you have a habbit of storing your images into a database, this technique useful. Simply, concatenate the date and time with image name and save it. Date and time are always different.
myImage.Src = ""
myImage.Src = "~/car.png" & "?" & DateTime.Now.Ticks.ToString    ' Add date time to prevent caching.

This process is simple, and you can easily get the name of the image by simply replacing the string after the ? character.

Well, that’s it. Thanks for reading.

← PreviousNext →

Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.
Delivered by FeedBurner