Click here to Skip to main content
Click here to Skip to main content

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

, 8 Jul 2004
Rate this:
Please Sign up or sign in to vote.
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. Smile | :)

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 Smile | :) )

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 Smile | :) ). 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 Smile | :)

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

Share

About the Author

Arunkumar Viswanathan
Software Developer Application Security Inc.
United States United States
Arunkumar Viswanathan is currently a software engineer at Application Security Inc. in New York City. His interests include electronics (especially audio), photography and anything that is interesting.

Comments and Discussions

 
QuestionEasier way Pinmemberpianocomposer16-Mar-12 7:25 
GeneralAdd Multiple Directories PinmemberBadBrad042-Mar-10 12:00 
GeneralRe: Add Multiple Directories PinmemberArunkumar Viswanathan5-May-10 11:56 
GeneralThank you sir for letting me reuse your work ! Pinmemberrodvin22-May-09 4:46 
GeneralAdded a "minimum count" section Pinmemberclark2225-Mar-09 6:44 
QuestionWhy do more work when you don't have to? PinmemberJeff Lorenzini17-Oct-07 12:33 
GeneralMy question Pinmembermpdesign3-Jun-07 23:27 
GeneralRe: My question Pinmember--XXX--4-Jun-07 6:42 
GeneralRe: My question Pinmembermpdesign4-Jun-07 7:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.141022.1 | Last Updated 9 Jul 2004
Article Copyright 2004 by Arunkumar Viswanathan
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid