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. -
public static DateTime GetRelativeDateTime(int days, int hours, int minutes)
-
{
-
return DateTime.Now.AddDays(-days).AddHours(-hours).AddMinutes(-minutes);
-
}
-
-
public static string[] FilesOlderThan(DateTime dt)
-
{
-
DirectoryInfo directory = new DirectoryInfo(Directory.GetCurrentDirectory());
-
FileInfo[] files = directory.GetFiles(); //get FileInfos for the files in the current directory
-
ArrayList older = new ArrayList(); //list to hold the result
-
foreach (FileInfo file in files)
-
{
-
if (file.CreationTime < dt) //if smaller (older) than the relative time
-
older.Add(file.Name); //add it to the list
-
}
-
}
-
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!!
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).
would this work? -
public int DeleteFilesOlderThan(int days, int hrs, int mins)
-
{
-
string[] older = FilesOlderThan(Days, Hrs, Mins);
-
int count = 0;
-
foreach (string file in files)
-
{
-
try
-
{
-
File.Delete(file);
-
count++;
-
}
-
catch (Exception e)
-
{
-
Console.WriteLine("Unable to delete " + file);
-
Console.WriteLine("Reason: {0}", e);
-
//Console.WriteLine("Detected an exception!!!\n" + e );
-
}
-
Console.WriteLine("Files successfully deleted");
-
}
-
// presumably number of files deleted to be returned
-
return count;
-
}
-
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.
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 -
using System;
-
using System.IO;
-
using System.Collections;
-
-
namespace Files_ExtLib1
-
{
-
public class FolderWatcher
-
{
-
string m_FolderPath;
-
-
public FolderWatcher()
-
{
-
//
-
// TODO: Add constructor logic here
-
//
-
}
-
-
#region Property
-
public string FolderPath
-
{
-
get
-
{
-
return m_FolderPath;
-
}
-
set
-
{
-
m_FolderPath = value;
-
}
-
}
-
#endregion
-
-
/// <summary>
-
/// Deletes the files older the days, hours, and
-
/// minutes specified
-
/// </summary>
-
/// <param name="Days"></param>
-
/// <param name="Hrs"></param>
-
/// <param name="Mins"></param>
-
/// <returns>Number of files deleted</returns>
-
public int DeleteFilesOlderThan(int Days, int Hrs, int Mins)
-
{
-
string[] oldFilePaths = FilesOlderThan(Days, Hrs, Mins);
-
int count = 0;
-
foreach (string filePath in oldFilePaths)
-
{
-
try
-
{
-
File.Delete(filePath);
-
count++;
-
}
-
catch (Exception e)
-
{
-
Console.WriteLine("Unable to delete " + filePath);
-
Console.WriteLine("Reason: {0}", e);
-
//Console.WriteLine("Detected an exception!!!\n" + e );
-
}
-
Console.WriteLine("Files successfully deleted");
-
}
-
// presumably number of files deleted to be returned
-
return count;
-
}
-
-
-
/// <summary>
-
/// Reurns filenames having last modified time older than
-
/// specified period.
-
/// </summary>
-
/// <param name="Days"></param>
-
/// <param name="Hrs"></param>
-
/// <param name="Mins"></param>
-
/// <returns></returns>
-
public string[] FilesOlderThan(int Days, int Hrs, int Mins)
-
{
-
TimeSpan ts = new TimeSpan(Days, Hrs, Mins, 0);
-
ArrayList oldFilePaths = new ArrayList();
-
// FolderPath is assumed to be path being watched
-
string[] filePaths = Directory.GetFiles(FolderPath);
-
DateTime currentDate = DateTime.Now;
-
foreach (string filePath in filePaths)
-
{
-
DateTime lastWriteDate = File.GetLastWriteTime(filePath);
-
if ((currentDate - lastWriteDate) > ts)
-
{
-
oldFilePaths.Add(filePath);
-
}
-
}
-
return (string[])oldFilePaths.ToArray(typeof(string));
-
}
-
}
-
}
-
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. -
static void Main(string[] args)
-
{
-
FolderWatcher fw = new FolderWatcher();
-
fw.FolderPath = @"c:\my documents\temp"; // or whatever
-
int days = int.Parse(args[0]);
-
int hrs = int.Parse(args[1]);
-
int mins = int.Parse(args[2]);
-
fw.DeleteFilesOlderThan(days,hrs,mins);
-
}
-
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
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
Are you only allowed to define one pattern? ie, "*.txt"? Or
can you define multiple patterns? ie, "*.txt; *.exe; *.log"?
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.
Sign in to post your reply or Sign up for a free account.
Similar topics |
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...
|
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;
|
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
|
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.
|
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.
| |
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...
|
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. ...
|
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;
|
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...
|
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...
|
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...
| |
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...
|
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...
|
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();...
|
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...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |