Hi all,
I have this piece of code that monitors a given folder and delete all files older that X number of days. I want to test it out on some sort of a dummy folder before i pass it to my team and they test it on real data. what do i do for that? first time doing this...Thanks for spending time!!
I have this piece of code that monitors a given folder and delete all files older that X number of days. I want to test it out on some sort of a dummy folder before i pass it to my team and they test it on real data. what do i do for that? first time doing this...Thanks for spending time!!
Code:
using System;
using System.IO;
using System.Windows.Forms;
using System.Collections;
namespace Files_ExtLib1
{
/// <summary>
/// Summary description for FolderWatcher.
/// </summary>
public class FolderWatcher
{
string m_FolderPath;
public FolderWatcher()
{
//
// TODO: Add constructor logic here
//
}
#region Property
public string FolderPath
{
get
{
return m_FolderPath;
}
set
{
m_FolderPath = value;
}
}
#endregion
// Deletes the files older the days, hours, and minutes specified
public int DeleteFilesOlderThan(int Days, int Hrs, int Mins)
{
string[] oldFilePaths = FilesOlderThan(Days, Hrs, Mins);
int count = 0;
foreach(string filePath in oldFilePaths)
{
try
{
File.Delete(filePath);
count++;
}
catch
{
MessageBox.Show("Unable to delete " + filePath);
}
}
// presumably number of files deleted to be returned
return count;
}
// Reurns filenames having last modified time older than specified period.
public string[] FilesOlderThan(int Days, int Hrs, int Mins)
{
TimeSpan ts = new TimeSpan(Days, Hrs, Mins, 0);
ArrayList oldFilePaths = new ArrayList();
// FolderPath is assumed to be path being watched
string[] filePaths = Directory.GetFiles(FolderPath);
DateTime currentDate = DateTime.Now;
foreach(string filePath in filePaths)
{
DateTime lastWriteDate = File.GetLastWriteTime(filePath);
if ((currentDate - lastWriteDate) > ts)
{
oldFilePaths.Add(filePath);
}
}
return (string[])oldFilePaths.ToArray(typeof(string));
}
}
}
Comment