C# 遍歷資料夾 刪除過期圖片
阿新 • • 發佈:2019-02-06
/// <summary>
/// 刪除過期的儲存圖片
/// </summary>
public void DeleteOTImg(string path)
{
try
{
DirectoryInfo theFolder = new DirectoryInfo(path);
DirectoryInfo[] dirInfo = theFolder.GetDirectories();
DateTime dtNow = DateTime.Now;
int saveDay = Convert.ToInt32(ConfigOperator.Single().StrSaveDays);
//遍歷資料夾
foreach (DirectoryInfo NextFolder in dirInfo)
{
//直接刪除資料夾以及檔案
/*TimeSpan ts = dtNow.Subtract(NextFolder.LastWriteTime);
if (ts.TotalDays > saveDay)//超過了儲存時間,刪除檔案
{
NextFolder.Delete(true);
}*/
FileInfo[] fileInfo = NextFolder.GetFiles("*.jpg", SearchOption.AllDirectories);
foreach (FileInfo tmpfi in fileInfo) //遍歷檔案
{
TimeSpan ts = dtNow.Subtract(tmpfi.LastWriteTime);
if (ts.TotalDays > saveDay)//超過了儲存時間,刪除檔案
{
tmpfi.Delete();
}
}
}
}
catch (Exception ex)
{
Trace.WriteLine(ex.Message);
}
}