public static string[] GetImages(string folder, int count)
{
HttpContext context = HttpContext.Current;
string virtualFolderPath = string.Format("{0}/", folder);
string absoluteFolderPath = context.Server.MapPath(virtualFolderPath);
Cache cache = context.Cache;
var images = cache[folder + "_images"] as List<string>;
// cache string array if it does not exist
if (images == null)
{
var di = new DirectoryInfo(absoluteFolderPath);
images = (from fi in di.GetFiles()
where fi.Extension.ToLower() == ".jpg" || fi.Extension.ToLower() == ".gif" || fi.Extension.ToLower() == ".png"
select string.Format("{0}{1}", virtualFolderPath, fi.Name))
.ToList();
// create cach dependency on image randomFolderName
cache.Insert(folder + "_images", images, new CacheDependency(absoluteFolderPath));
}
Random random = new Random((int)DateTime.Now.Ticks);
var imageSet = new HashSet<string>();
if (count > images.Count())
{
throw new ArgumentOutOfRangeException("count");
}
while (imageSet.Count() < count)
{
//using an hashset will ensure a random set with unique values.
imageSet.Add(images[random.Next(images.Count())]);
}
return imageSet.ToArray();
}