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. -
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 3386
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;
-
}
-
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.
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.cs 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 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
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
Are you only allowed to define one pattern? ie, "*.txt"? Or
can you define multiple patterns? ie, "*.txt; *.exe; *.log"?
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...
|
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...
|
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...
|
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.
...
|
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...
|
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...
|
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 -...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
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...
|
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...
|
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,...
|
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,...
|
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...
|
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...
|
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,...
|
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...
| |