Delete all image file from Perticular folder in C#


Friday, March 19, 2010

Hello DotNet Developer,

Please find below code, which will help to find all file in perticular folder and delete all the file and make folder blank.

Explaination of the code : Delete all image file from Perticular folder in C#

Here, i have find the folder path using Server.MapPath, then stored all the file in the array, i have named it imglist.

Then i have used forloop to get all the files name one by one and delete it,
Here i have taken DateTime.Now.AddMinutes, because if the file is added just before 3 minutes from the current time, then it should not be delete, you can change the time according to your need.

Code :

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();
}
}
}



Hope this post will help you,
if yes please put comment below of this page,
Rajesh Singh,
Asp.Net Developer
Indianic Infotech Ltd (India)
rajesh@indianic.com

1 comment :

Vijyeta said...

Thanks . It is very useful