By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
425,542 Members | 1,740 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 425,542 IT Pros & Developers. It's quick & easy.

C#: add/show delete method using date time object

P: 45
Hi there,

I have a FolderWatcher.cs class that will monitor a given folder and delete files older than X number of days. I have the following methods. I need to add/show delete mothod using date time object.

Expand|Select|Wrap|Line Numbers
  1.         public static DateTime GetRelativeDateTime(int days, int hours, int minutes)
  2.         {
  3.             return DateTime.Now.AddDays(-days).AddHours(-hours).AddMinutes(-minutes);
  4.         }
  5.  
  6.         public static string[] FilesOlderThan(DateTime dt)
  7.         {
  8.             DirectoryInfo directory = new DirectoryInfo(Directory.GetCurrentDirectory());
  9.             FileInfo[] files = directory.GetFiles(); //get FileInfos for the files in the current directory 
  10.             ArrayList older = new ArrayList(); //list to hold the result 
  11.             foreach (FileInfo file in files)
  12.             {
  13.                 if (file.CreationTime < dt) //if smaller (older) than the relative time 
  14.                     older.Add(file.Name); //add it to the list 
  15.             }
  16.         }
  17.  
i want to know couple of other stuff as well..returning an array list instead of string[] is better or not? What is the difference between timespan object and DateTime object?..Are there any benefits of using timespan object instead of datetime object?

Thanks in advance for the help!!
Dec 4 '07 #1
Share this Question
Share on Google+
7 Replies


Plater
Expert 5K+
P: 7,872
Either the FileInfo of File class (or both?) has a .Delete() function I believe, so you could just call that for each of your files that is too old.

They are just as they sound DateTime represents a specific DateTime in real life(December 1st, 2006 3:45 AM), whereas a TimeSpan just represents an amount of time (42mins 36seconds).
Dec 4 '07 #2

P: 45
would this work?

Expand|Select|Wrap|Line Numbers
  1.         public int DeleteFilesOlderThan(int days, int hrs, int mins)
  2.         {
  3.             string[] older = FilesOlderThan(Days, Hrs, Mins);
  4.             int count = 0;
  5.             foreach (string file in files)
  6.             {
  7.                 try
  8.                 {
  9.                     File.Delete(file);
  10.                     count++;
  11.                 }
  12.                 catch (Exception e)
  13.                 {
  14.                     Console.WriteLine("Unable to delete " + file);
  15.                     Console.WriteLine("Reason: {0}", e);
  16.                     //Console.WriteLine("Detected an exception!!!\n" + e );
  17.                 }
  18.                 Console.WriteLine("Files successfully deleted");
  19.             }
  20.             // presumably number of files deleted to be returned
  21.             return count;
  22.         }
  23.  
Dec 4 '07 #3

Plater
Expert 5K+
P: 7,872
it looks like it should, assuming your function that finds old files is correct.
does that string[] contain filenames like "C:\mydirectory\somefile.txt" or does it just contain "somefile.txt", because I believe you will need a fully qualified path for it to work correctly.
Dec 4 '07 #4

P: 45
I checked this peice of code using cosole application and it worked. I used a different coding method though. This is the class that monitors and deletes Files older than X number of days
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.IO;
  3. using System.Collections;
  4.  
  5. namespace Files_ExtLib1
  6. {
  7.     public class FolderWatcher
  8.     {
  9.         string m_FolderPath;
  10.  
  11.         public FolderWatcher()
  12.         {
  13.             //
  14.             // TODO: Add constructor logic here
  15.             //
  16.         }
  17.  
  18.         #region Property
  19.         public string FolderPath
  20.         {
  21.             get
  22.             {
  23.                 return m_FolderPath;
  24.             }
  25.             set
  26.             {
  27.                 m_FolderPath = value;
  28.             }
  29.         }
  30.         #endregion
  31.  
  32.         /// <summary>
  33.         /// Deletes the files older the days, hours, and
  34.         /// minutes specified
  35.         /// </summary>
  36.         /// <param name="Days"></param>
  37.         /// <param name="Hrs"></param>
  38.         /// <param name="Mins"></param>
  39.         /// <returns>Number of files deleted</returns>
  40.         public int DeleteFilesOlderThan(int Days, int Hrs, int Mins)
  41.         {
  42.             string[] oldFilePaths = FilesOlderThan(Days, Hrs, Mins);
  43.             int count = 0;
  44.             foreach (string filePath in oldFilePaths)
  45.             {
  46.                 try
  47.                 {
  48.                     File.Delete(filePath);
  49.                     count++;
  50.                 }
  51.                 catch (Exception e)
  52.                 {
  53.                     Console.WriteLine("Unable to delete " + filePath);
  54.                     Console.WriteLine("Reason: {0}", e);
  55.                     //Console.WriteLine("Detected an exception!!!\n" + e );
  56.                 }
  57.                 Console.WriteLine("Files successfully deleted");
  58.             }
  59.             // presumably number of files deleted to be returned
  60.             return count;
  61.         }
  62.  
  63.  
  64.         /// <summary>
  65.         /// Reurns filenames having last modified time older than
  66.         /// specified period.
  67.         /// </summary>
  68.         /// <param name="Days"></param>
  69.         /// <param name="Hrs"></param>
  70.         /// <param name="Mins"></param>
  71.         /// <returns></returns>
  72.         public string[] FilesOlderThan(int Days, int Hrs, int Mins)
  73.         {
  74.             TimeSpan ts = new TimeSpan(Days, Hrs, Mins, 0);
  75.             ArrayList oldFilePaths = new ArrayList();
  76.             // FolderPath is assumed to be path being watched
  77.             string[] filePaths = Directory.GetFiles(FolderPath);
  78.             DateTime currentDate = DateTime.Now;
  79.             foreach (string filePath in filePaths)
  80.             {
  81.                 DateTime lastWriteDate = File.GetLastWriteTime(filePath);
  82.                 if ((currentDate - lastWriteDate) > ts)
  83.                 {
  84.                     oldFilePaths.Add(filePath);
  85.                 }
  86.             }
  87.             return (string[])oldFilePaths.ToArray(typeof(string));
  88.         }
  89.     }
  90. }
  91.  
and it worked perfectly fine when i pass the parameters using command line arguments to the executable. I checked the FolderWatcher.cs class on a dummy folder.
Expand|Select|Wrap|Line Numbers
  1. static void Main(string[] args)
  2.    {
  3.       FolderWatcher fw = new FolderWatcher();
  4.       fw.FolderPath = @"c:\my documents\temp"; // or whatever
  5.       int days = int.Parse(args[0]);
  6.       int hrs = int.Parse(args[1]);
  7.       int mins = int.Parse(args[2]);
  8.       fw.DeleteFilesOlderThan(days,hrs,mins);       
  9.    }
  10.  
My colleague wanted me to do the whole procedue using DateTime object. So, I have created the two methods for that which I already included in my first post. I just want to know how do i create a DeleteFilesOlderThan method using DateTime object. Is it possible to create method that can create test files with different format lets say .log, .txt, .exe and have another method to delete specific file type e.g delete .txt files only or .exe or .log
I just want to add more functionality to FolderWatcher.cs class because I want to use it with prod where we deal with like 10,000 files at once and have to delete like 10 for example....
Thanks for your time
Dec 4 '07 #5

Plater
Expert 5K+
P: 7,872
Well using the DateTime object you could just compare it against the the file datetime to see if it's older.
So if you passed in a datetime object: {December 12th, 2006 12:51 AM} you would do your comparison with the passed in datetime object, INSTEAD of doing the .AddDays() etc.

Directory.GetFiles(FolderPath) should also take a "pattern" argument that would allow you to do "*.txt" to only get filesnames that end in .txt
Dec 4 '07 #6

P: 45
Are you only allowed to define one pattern? ie, "*.txt"? Or
can you define multiple patterns? ie, "*.txt; *.exe; *.log"?
Dec 4 '07 #7

Plater
Expert 5K+
P: 7,872
Are you only allowed to define one pattern? ie, "*.txt"? Or
can you define multiple patterns? ie, "*.txt; *.exe; *.log"?
I *think* it's only one pattern.
BUT, you could call it a bunch of times and keep joining them together.
Dec 5 '07 #8

Post your reply

Sign in to post your reply or Sign up for a free account.