Click here to Skip to main content
15,881,413 members
Articles / Programming Languages / C#
Article

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

Rate me:
Please Sign up or sign in to vote.
2.94/5 (7 votes)
8 Jul 20043 min read 70.5K   1K   21   9
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:

C#
//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


Written By
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 Pin
pianocomposer16-Mar-12 7:25
pianocomposer16-Mar-12 7:25 
GeneralAdd Multiple Directories Pin
BadBrad042-Mar-10 12:00
BadBrad042-Mar-10 12:00 
GeneralRe: Add Multiple Directories Pin
Arunkumar Viswanathan5-May-10 11:56
Arunkumar Viswanathan5-May-10 11:56 
GeneralThank you sir for letting me reuse your work ! Pin
rodvin22-May-09 4:46
rodvin22-May-09 4:46 
GeneralAdded a "minimum count" section Pin
ClarkBohs25-Mar-09 6:44
ClarkBohs25-Mar-09 6:44 
QuestionWhy do more work when you don't have to? Pin
Jeff Lorenzini17-Oct-07 12:33
Jeff Lorenzini17-Oct-07 12:33 
GeneralMy question Pin
mpdesign3-Jun-07 23:27
mpdesign3-Jun-07 23:27 
GeneralRe: My question Pin
Arunkumar Viswanathan4-Jun-07 6:42
Arunkumar Viswanathan4-Jun-07 6:42 
GeneralRe: My question Pin
mpdesign4-Jun-07 7:44
mpdesign4-Jun-07 7:44 

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

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