Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Console App for deleting files in a specified directory based on user inputted timestamp

0.00/5 (No votes)
8 Jul 2004 3  
Very useful in running as a scheduled task to delete unwanted files accumulating in a directory

Introduction

The need for this code arose when one of my team members needed a script to delete files based on the time he specified. He had a directory that kept accumulating too many junk files and he had to manually go in and check each of the file's last modified time and delete them. :)

Though a similar app like this is bound to exist somewhere I just chose to write this one for the sake of fun.

Using the code

Since this is a console application all you have to do is compile the code and run the exe to test the basic application. The "DelFiles.exe" command deletes the files present in a specified directory depending on the time difference between the system time and the user specified time.

The logic is very simple. The user specified time span is added to the file's last write time. This calculated time represents the time after which the file has to be deleted. So if the system time exceeds the calculated file time, it means the file's life has ended and it is deleted.

The default values I have set are:

Initial Directory: C:\SomeDirectory (This will obviously throw an error message :))

Time to be added to the last write time: 30 minutes

The switches for the command are as follows. All the switches are optional.

delfiles [/dir=] [/d=] [/h=] [/m=] [/s=] [/?] 
  • [/dir=] --> Enter the COMPLETE PATH of the directory. example: c:\www\myDirectory
  • [/d=] --> Enter the number of days as an integer value. Max value is 60. Above 60 the value defaults to 0.
  • [/h=] --> Enter the number of hours as an integer value. Max value is 48. Above 48 the value defaults to 0.
  • [/m=] --> Enter the number of minutes as an integer value. Max value is 120. Above 120 the value defaults to 30.
  • [/s=] --> Enter the number of seconds as an integer value. Max value is 300. Above 120 the value defaults to 0.
  • [/?] --> Shows you the help screen

Note: If you include a value for days as well as minutes etc. options, they will be added to your final timestamp value.

The key section of the code is as shown below:

//Run through every file and delete if needed.

//If no files then no problems. The program stops thats all.

//==============================

foreach (FileInfo f in dirInfo.GetFiles())
{
    Console.WriteLine("{0,40}{1,10}{2,25}",
        f.Name, f.Length, f.LastWriteTime);
    
    DateTime systemDt = DateTime.Now;
    DateTime fileDt = f.LastWriteTime;
    DateTime cpmTime;
    //IF SYSTEM TIME < FILE WRITE TIME - send a warning message

    //since anyway the file won't be deleted with the current logic

    if (f.LastWriteTime > systemDt)
        Console.WriteLine("Some one messed the system clock or "+
        "the file write time was in a different time zone!!!");

    //USE THE DEFAULT VALUES

    if (boolDefaultTime == true)
    {
        cpmTime = fileDt + diffTSpan;                                
    }
    else    //USING USER INPUTTED VALUES

    {
        TimeSpan customTSpan = new TimeSpan(intDays,
          intHours, intMinutes, intSeconds);
        cpmTime = fileDt + customTSpan;                                
    }                            

    Console.WriteLine(cpmTime.ToLongDateString());
    Console.WriteLine(cpmTime.ToLongTimeString());
                            
    //CHECKING IF THE FILE LIFE TIME IS MORE THAN THE

    //CURRENT SYSTEM TIME. IF YES FILE IS VALID

    if (DateTime.Compare(cpmTime, systemDt) > 0)
        Console.WriteLine("Still Valid!");
    else    //CHECKING IF THE FILE LIFE TIME IS <= THE

    //CURRENT SYSTEM TIME. IF YES - FILE IS SET FOR DELETION

    {
        Console.WriteLine("{0} file is being deleted!", f.Name);
        f.Delete();
        Console.WriteLine("{0} file has been deleted!", f.Name);
    }
    
    Console.WriteLine("\n");
    
}

Points of Interest

This is a very simple application but it is very useful. You can modify the code so that you can accept an array of directories you want to monitor. You can also make the code recurse through sub directories present in a directory or directories. The above tasks can easily be customized according to your needs (I am providing only the basic framework :)). Once you are done with customizations, compile the code to generate an exe. Then write a simple batch file with the appropriate timestamp and run it through the windows scheduler. So everytime the task runs, the latest write times for all the files in your specified folders are added to your predefined timestamp and then compared to the system time. When a file's time is up it is deleted!

I have attached a sample batch file called test.bat in the demo zip file. Be sure to give the correct directory name. Otherwise some of your important files will be deleted in front of your eyes and there is nothing you can do about it except may be laugh at yourself :)

About Me

A simple person seeking out a living by programming ^_^

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here