Simple Rotating Ad Script in ASP.NET

Date: 19 Feb 2010 Comments: 0

In the home page, you can see ‘Your Ad Here’ image. If you go to another page, you’ll see another ‘Your Ad Here’ image. Here’s an example of rotating ad banners that you can use in your asp.net website:

1. You’ll need a folder in you web server with all the image ads in it. But this folder should contain Only the ads images and nothing else, ex. /images/ads/

2. In the aspx page the following code:

<a href=”your_ad_url”>
<%= GetYourAdHere() %>
</a>

replace your_ad_url with url you want. We need to write implementation of the GetYourAdHere method:

3. In the code behind class add the following code:

using System.IO;

private const string _IMAGES_AD_PATH = “~/images/ads/”;
private const string _IMG_AD_TAG = “<img src=\”http://www.devtheweb.net/images/ads/XXX\” alt=\”Your Ad Here\” />”;

private static int adIndex = 0;

public string GetYourAdHere()
{
DirectoryInfo di;
FileInfo[] imgAds;
string result = “”;

try
{
di = new DirectoryInfo(Server.MapPath(_IMAGES_AD_PATH));

//t get images files
imgAds = di.GetFiles();

result = _IMG_AD_TAG.Replace(“XXX”, imgAds[adIndex].Name);

if (adIndex < imgAds.Count() – 1)
++adIndex;
else
adIndex = 0;
}
catch (Exception)
{
}

return result;
}

_IMAGES_AD_PATH is the path of folder with image ads.

_IMG_AD_TAG is template of the image tag, you can modify how you want, only XXX is used to be replaced with the image name.

The code should works for you if you change only these two const variables’ values. Here’s an explanation about the other part of the code:

adIndex is a static variable which we use to store the current index of the ads images. It’s increased with 1 every time the banner ad is shown. That’s how we rotate the banners :)

Leave a Reply


Spam protection by WP Captcha-Free