Home > Uncategorized > c# delete files and directories modified before X days

c# delete files and directories modified before X days

A quick program that deletes files and folders (optionally recursive) modified more than N days ago.

Yes! I use variables that are at the root namespace area or whatever.

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Mail;

namespace DeleteModDateOlderThan
{
    class Program
    {
        static string EmailRecipients = "";

        static void Main(string[] args)
        {

            string TargetDirectory = "";
            int DaysOld = 0;
            bool RecursivePlz = false;
            List ItemsDeleted = new List();
            

            bool skipdir = false; //because the directory check is probably latent

            switch (args.Length)
            {
                case 0:
                    Console.WriteLine("Give me some food.");
                    Console.WriteLine("Usage: DeleteModDate.exe [-r] directory -d [N days] [-e [comma-separated email address list or one]]");
                    Console.WriteLine("-r (recursive) is not required.  email list is not required.");
                    Environment.Exit(-1);
                    break;

                case 1: //there are three arguments needed (directory, "-d", number of days)
                    goto case 0;
 
                case 2: //there are at least three arguments needed (directory, "-d", number of days)
                    goto case 0;

                case 3: //if there are three arguments, none of them should be "-r" or "-e"
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (args[i] == "-r")
                        {
                            goto case 0;
                        }
                        
                        if (args[i] == "-e")
                        {
                            goto case 0;
                        }
                        
                        if (skipdir == false)
                        {
                            if (Directory.Exists(args[i]))
                            {
                                skipdir = true;
                                TargetDirectory = args[i];
                            }
                        }

                        if (args[i] == "-d")
                        {
                            if (int.TryParse(args[i+1], out DaysOld)) //set daysold to the number of days listed
                            {
                                //then args[2] is a number!
                                i = i + 1; //skip over parsing the N day argument

                            }
                            else
                            {
                                Console.WriteLine("You must provide a number with -d.");
                                goto case 0;
                            }
                        }
                    }

                    break;

                case 4: //if there are four arguments, then "-r" is expected, "-e" is unexpected
                    for (int i =0; i < args.Length; i++)
                    {
                        if (args[i] == "-r")
                        {
                            RecursivePlz = true;
                        }
                        
                        if (args[i] == "-e")
                        {
                            goto case 0;
                        }
                        
                        if (skipdir == false)
                        {
                            if (Directory.Exists(args[i]))
                            {
                                skipdir = true;
                                TargetDirectory = args[i];
                            }
                        }


                        if (args[i] == "-d")
                        {
                            if (int.TryParse(args[i + 1], out DaysOld)) //set daysold to the number of days listed
                            {
                                //then args[2] is a number!
                                i = i + 1; //skip over parsing the N day argument

                            }
                            else
                            {
                                Console.WriteLine("You must provide a number with -d.");
                                goto case 0;
                            }
                        }
                    }
                    break;


                case 5: //if there are five arguments, then "-e" is expected, followed by something with '@' and '.' in it (if this thing contains ',' cool), "-r" is unexpected
                    for (int i = 0; i  0)
                            {
                                if (args[i + 1].Contains("@") & args[i + 1].Contains("."))
                                {
                                    EmailRecipients = args[i + 1].ToString();
                                }
                            }
                            else
                            {
                                goto case 0;
                            }
                        }
                        
                        if (skipdir == false)
                        {
                            if (Directory.Exists(args[i]))
                            {
                                skipdir = true;
                                TargetDirectory = args[i];
                            }
                        }


                        if (args[i] == "-d")
                        {
                            if (int.TryParse(args[i + 1], out DaysOld)) //set daysold to the number of days listed
                            {
                                //then args[2] is a number!
                                i = i + 1; //skip over parsing the N day argument

                            }
                            else
                            {
                                Console.WriteLine("You must provide a number with -d.");
                                goto case 0;
                            }
                        }

                    }
                    break;


                case 6: //if there are six arguments, all arguments are expected
                    for (int i = 0; i  0)
                            {
                                if (args[i + 1].Contains("@") & args[i + 1].Contains("."))
                                {
                                    EmailRecipients = args[i + 1].ToString();
                                }
                            }
                            else
                            {
                                goto case 0;
                            }
                        }
                        
                        if (skipdir == false)
                        {
                            if (Directory.Exists(args[i]))
                            {
                                skipdir = true;
                                TargetDirectory = args[i];
                            }
                        }


                        if (args[i] == "-d")
                        {
                            if (int.TryParse(args[i + 1], out DaysOld)) //set daysold to the number of days listed
                            {
                                //then args[2] is a number!
                                i = i + 1; //skip over parsing the N day argument

                            }
                            else
                            {
                                Console.WriteLine("You must provide a number with -d.");
                                goto case 0;
                            }
                        }

                    }
                    break;
                default:
                    goto case 0;

            }

            if (EmailRecipients.Length > 0)
            {
                SendEmail(CheckFiles(TargetDirectory, DaysOld, RecursivePlz, ItemsDeleted));
            }
            else
            {
                CheckFiles(TargetDirectory, DaysOld, RecursivePlz, ItemsDeleted);
            }
        }


        public static List CheckFiles(string TargetDirectory, int DaysOld, bool RecursivePlz, List ItemsDeleted)
        {

            TargetDirectory = TargetDirectory.ToLower();

            if (!TargetDirectory.Contains("dfsrprivate"))
            {

                //find the directory
                if (Directory.Exists(TargetDirectory))
                {
                    //find the files in this directory
                    string[] FileList = Directory.GetFiles(TargetDirectory);


                    //check and delete files in this directory
                    foreach (string ffile in FileList)
                    {
                        //get last write time
                        DateTime LastWritedt = File.GetLastWriteTime(ffile);
                        DateTime TimeNow = DateTime.Now;

                        TimeSpan LastWrite = TimeNow.Subtract(LastWritedt);
                        TimeSpan HowManyDays = TimeSpan.FromDays(DaysOld);
                        if (LastWrite > HowManyDays)
                        {
                            try
                            {
                                //File.Delete(ffile);
                                ItemsDeleted.Add(ffile);
                                Console.WriteLine(ffile + " deleted.");
                            }
                            catch (Exception ex)
                            {
                                ItemsDeleted.Add("FAILED DELETE: " + ffile + " " + ex.Message);
                                Console.WriteLine("FAILED DELETE: " + ffile + " " + ex.Message);
                            }
                        }

                    }

                    //find all the sub-directories in the directory
                    string[] SubDirectorylist = Directory.GetDirectories(TargetDirectory);

                    //reverse the entire list
                    Array.Reverse(SubDirectorylist);

                    //find the files in this directory again
                    FileList = Directory.GetFiles(TargetDirectory);

                    //if this directory is empty, delete it
                    if (FileList.Length == 0 && SubDirectorylist.Length == 0)
                    {
                        try
                        {
                            //Directory.Delete(TargetDirectory);
                            ItemsDeleted.Add(TargetDirectory);
                            Console.WriteLine(TargetDirectory + " is empty. Deleted.");
                        }
                        catch (Exception ex)
                        {
                            ItemsDeleted.Add("FAILED DELETE: " + TargetDirectory + " " + ex.Message);
                            Console.WriteLine("FAILED DELETE: " + TargetDirectory + " " + ex.Message);
                        }
                    }




                    //if user has requested recursive action, go ahead...
                    if (RecursivePlz == true)
                    {
                        if (Directory.Exists(TargetDirectory))
                        {
                            //trigger CheckFiles() on these as well
                            foreach (string ddir in SubDirectorylist)
                            {
                                CheckFiles(ddir, DaysOld, RecursivePlz, ItemsDeleted);
                            }
                        }
                    }
                }
            }

            return ItemsDeleted;
        }

        public static void SendEmail(List DeletedList)
        {

            MailMessage message = new MailMessage();
            message.From = new MailAddress("fs-gremlin@domain.com", "fs-gremlin");

            foreach (string EmailAddress in EmailRecipients.Split(','))
            {
                message.To.Add(EmailAddress);
            }


            message.Body = "This is the list of files and folders deleted: \n";

            foreach (string listentry in DeletedList)
            {
                message.Body = message.Body + "\n" + listentry;
            }

            message.Subject = "File deletion report";

            SmtpClient smtpInstance = new SmtpClient
            {
                Host = "mail.domain.com",
                Port = 25,
                Timeout = 120000,
                DeliveryMethod = SmtpDeliveryMethod.Network
            };

            smtpInstance.Send(message);
        }
    }
}

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: