Delete files from the folder older than 4 days

风流意气都作罢 提交于 2019-12-08 01:57:01

问题


I would like to run a timer for every 5 hours and delete the files from the folder older than 4 days. Could you please with sample code?


回答1:


Since it hasn't been mentioned, I would recommend using a System.Threading.Timer for something like this. Here's an example implementation:

System.Threading.Timer DeleteFileTimer = null;

private void CreateStartTimer()
{
    TimeSpan InitialInterval = new TimeSpan(0,0,5);
    TimeSpan RegularInterval = new TimeSpan(5,0,0);

    DeleteFileTimer = new System.Threading.Timer(QueryDeleteFiles, null, 
            InitialInterval, RegularInterval);

}

private void QueryDeleteFiles(object state)
{
    //Delete Files Here... (Fires Every Five Hours).
    //Warning: Don't update any UI elements from here without Invoke()ing
    System.Diagnostics.Debug.WriteLine("Deleting Files...");
}

private void StopDestroyTimer()
{
    DeleteFileTimer.Change(System.Threading.Timeout.Infinite,
    System.Threading.Timeout.Infinite);

    DeleteFileTimer.Dispose();
}

This way, you can run your file deletion code in a windows service with minimal hassle.




回答2:


DateTime CutOffDate = DateTime.Now.AddDays(-4)
DirectoryInfo di = new DirectoryInfo(folderPath);
FileInfo[] fi = di.GetFiles();

for (int i = 0; i < fi.Length; i++)
{
    if (fi[i].LastWriteTime < CutOffDate)
    {
        File.Delete(fi[i].FullName);
    }
}

You can substitute LastWriteTime property for something else, that's just what I use when clearing out an Image Cache in an app I have.

EDIT:

Though this doesnt include the timer part... I'll let you figure that part out yourself. A little Googling should show you several ways to do it on a schedule.



来源:https://stackoverflow.com/questions/1374094/delete-files-from-the-folder-older-than-4-days

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!