Hi All,
I have the following class which deletes files older than X number of days and with specific extension. I dont see any error in the code from my point of you. Please, can anyone double check for me because when i m debuging it, files are not getting deleted. Thanks:)
Entry point
I have the following class which deletes files older than X number of days and with specific extension. I dont see any error in the code from my point of you. Please, can anyone double check for me because when i m debuging it, files are not getting deleted. Thanks:)
Code:
using System;
using System.IO;
using System.Collections;
namespace Files_ExtLib1
{
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
public int DeleteFilesOlderThan(int Days, int Hrs, int Mins, string filter)
{
DateTime dt = GetRelativeDateTime(Days, Hrs, Mins);
ArrayList oldFilePaths = FilesOlderThan(dt, filter);
int count = 0;
foreach (string filePath in oldFilePaths)
{
try
{
File.Delete(filePath);
count++;
}
catch (Exception e)
{
Console.WriteLine("Unable to delete " + filePath);
Console.WriteLine("Reason: {0} ", e);
}
Console.WriteLine("Files successfully deleted");
}
return count;
}
// Using GetRelativeDateTime as a private method instead of public however as it is only to be used internally
private static DateTime GetRelativeDateTime(int days, int hours, int minutes)
{
return DateTime.Now.AddDays(-days).AddHours(-hours).AddMinutes(-minutes);
}
public ArrayList FilesOlderThan(DateTime dt, string filter)
{
// Using the supplied path
DirectoryInfo directory = new DirectoryInfo(m_FolderPath);
// Filter is applied to the directory.GetFiles method to get files of given extension
// get FileInfos for the files in the current directory matching the filter expression
FileInfo[] files = directory.GetFiles(filter);
//list to hold the result
ArrayList older = new ArrayList();
foreach (FileInfo file in files)
{
//if smaller (older) than the relative time
if (file.CreationTime < dt)
older.Add(file.Name); //add it to the list
}
return older;
}
}
}
Code:
private void DeleteFiles_Click(object sender, EventArgs e)
{
FolderWatcher fw = new FolderWatcher();
fw.FolderPath = @"c:\csharp"; // FolderName
//OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
fw.DeleteFilesOlderThan(int.Parse(Textbox1.Text), int.Parse(Textbox2.Text), int.Parse(Textbox3.Text), "*" + filetype.SelectedItem.ToString()); // deletes everything older than specified days,hrs, and mins respectively
//fw.DeleteFilesOlderThan(0, 0, 0, "*.txt");
}