473,797 Members | 3,212 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

45 New Member
Hi there,

I have a FolderWatcher.c s 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 3412
Plater
7,872 Recognized Expert Expert
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
Shani Aulakh
45 New Member
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 Recognized Expert Expert
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.t xt", because I believe you will need a fully qualified path for it to work correctly.
Dec 4 '07 #4
Shani Aulakh
45 New Member
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.c s 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 DeleteFilesOlde rThan 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.c s 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 Recognized Expert Expert
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.GetFi les(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
Shani Aulakh
45 New Member
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 Recognized Expert Expert
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
5408
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 virtual destructor. The class with the virtual destructor has AddRef() and Release() methods, and Release() ultimately does a "delete this". Can that "delete this" statement somehow find the right delete method? If it does, it involves a downcast...
2
9367
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 the function exits do i have a memory leak or other trouble brewing? ie: function MyFn() { var mydate;
9
5725
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
6112
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 not sure if there is a way to display all the months of an year? Please let me know. Thanks, Sridhar.
22
4195
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. How can I delete the node from DOM in other way? Thanks.
5
3114
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 the row. The Delete method marks the row as Deleted in the DataSet or DataTable but does not remove it. Instead when the DataAdapter encounters a row marked as Deleted, it executes its DeleteCommand method to delete the row at the data source. The...
22
3094
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 created / destroyed at user request). I can check form != null to prevent incorrect access. But, the form could disappear immediately after the check, before the method is run. Or someone could click 'close' when it's in the middle of an update. ...
15
5027
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 - but for the sake of this post ... I'm searching for an answer that assumes said decision. If I allocate memory in the class declaration: char buffer;
0
9685
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10469
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10023
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9066
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7560
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6803
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5459
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3750
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2934
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.