When I first wrote the original version of the
Mask Email Image Generator (Email Obfuscator), I didn't bother to add any code to periodically remove the images from the server. Yesterday I discovered it had almost 50,000 images in that folder. Not to repeat the same mistake, I wrote a function to delete image files that are older than 3 minutes. Sample code follows.
protected void CleanImageFolder()
{
string imgFolder = Server.MapPath("~/lab/maskemail/img/");
string[] imgList = Directory.GetFiles(imgFolder, "*.jpg");
foreach (string img in imgList)
{
FileInfo imgInfo = new FileInfo(img);
if (imgInfo.LastWriteTime < DateTime.Now.AddMinutes(-3))
{
imgInfo.Delete();
}
}
}Labels: ASP.NET, Csharp, Directory, FileInfo