473,406 Members | 2,954 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

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

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
7 3386
Plater
7,872 Expert 4TB
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
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
7,872 Expert 4TB
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
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
7,872 Expert 4TB
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
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
7,872 Expert 4TB
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

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

Similar topics

2
by: Ian McBride | last post by:
(was: delete() confusion) I have a class with multiple base classes. One of these base classes (base1) has its own new/delete operators and nothing else. Another base class (base 2) has a...
2
by: Eric | last post by:
Hi, I'm used to C/C++ where if you "new" something you really need to "delete" it later. Is that also true in javascript? if i do "mydate = new date();" in a function and dont "delete mydate" when...
9
by: Melissa | last post by:
What is the code to delete a command button from a form? Can the code be run from the click event of the button to be deleted? Thanks! Melissa
6
by: Sridhar | last post by:
Hi, I need to display a calendar that shows all the months of an year. In that, I need to show different colors for certain events. I know how to display a calendar for a certain month but I am...
22
by: Cylix | last post by:
I have a 4row x 1col table, I would like to drop all the content of row three. Since Mac IE5.2 does not suppport deleteRow method, I have also try to set the innerHTML=''; but it does not work. ...
5
by: rn5a | last post by:
The .NET 2.0 documentation states the following: When using a DataSet or DataTable in conjunction with a DataAdapter & a relational data source, use the Delete method of the DataRow to remove...
22
by: Zytan | last post by:
I have public methods in a form. The main form calls them, to update that form's display. This form is like a real-time view of data that is changing. But, the form may not exist (it is...
15
by: LuB | last post by:
I am constantly creating and destroying a singular object used within a class I wrote. To save a bit of time, I am considering using 'placement new'. I guess we could also debate this decision -...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.