Digital Colony!

Delete Files using C#

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: , , ,

AddThis Social Bookmark Button

8 Comments:

Anonymous Anonymous said...

Great job thanks for posting it, clear short and good solution. I only will add to it: try catch... if something goes wrong

8/29/2007 8:25 AM

Anonymous Anonymous said...

great job thanks for posting it, clear fast and good solution

8/29/2007 8:26 AM

Blogger the mission: said...

Great script! used it to clean up a folder we use to store automaticly generated xml files. A real time saver. Thanks!

11/13/2007 9:03 AM

Anonymous Anonymous said...

super great !!!! :)

11/22/2007 9:25 AM

Anonymous Anonymous said...

Thanks a lot.. It definitely just solved my problem...

God Bless! :)

3/18/2008 8:05 PM

Anonymous Javier Castonara said...

Smart script. Works beautifull!

4/01/2008 4:47 AM

Anonymous Raj said...

Extremely useful. Thanks!

4/04/2008 6:58 AM

Blogger Dinesh said...

great piece of script. i had been searching for such a script for the past few days..

thanx a lot..

11/03/2008 7:55 PM

 

Post a Comment

 

Digital Colony Copyright © 1999-2008 XHTML   508
This site uses Blogger, which is not 100% XHTML compliant.
Try...Catch Disclaimer: For brevity many examples do not include error handling. That is your responsibility.