Hi All,
Is it the right way of handling exception in a method? -
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;
-
}
-
13 1678
That looks like a pretty solid handling to me.
Thanks, But when i debug the application, the files get deleted but i dont see the msg showing Files successfully deleted.
can you check if this is coded properly using date time object -
public static DateTime GetRelativeDateTime(int days, int hours, int minutes)
-
{
-
return DateTime.Now.AddDays(-days).AddHours(-hours).AddMinutes(-minutes);
-
}
-
-
public int DeleteFilesOlderThan(DateTime dt)
-
{
-
string[] older = FilesOlderThan(dt);
-
int count = 0;
-
foreach (string file in files)
-
{
-
try
-
{
-
File.Delete(file.Name);
-
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;
-
}
-
-
public static string[] FilesOlderThan(DateTime dt)
-
{
-
DirectoryInfo directory = new DirectoryInfo(Directory.GetCurrentDirectory());
-
FileInfo[] files = directory.GetFiles(FolderPath); //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
-
}
-
}
-
Thanks, But when i debug the application, the files get deleted but i dont see the msg showing Files successfully deleted.
Does it show the messages you print out in your catch {} block?
Before when i was compiling the application, it was showing in pending checkins that files successfully deleted. but not anymore:S
okay i did some modification in my class...but its not deleting specific files from event handler...
[code]
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
public int DeleteFilesOlderThan(int Days, int Hrs, int Mins, string filter)
{
DateTime dt = GetRelativeDateTime(Days, Hrs, Mins);
ArrayList oldFilePaths = FilesOlderThan(dt, filter);
int count = 0;
foreach (string filePath in oldFilePaths)
{
try
{
File.Delete(filePath);
count++;
}
catch (Exception e)
{
Console.WriteLine("Unable to delete {0}", filePath);
Console.WriteLine("Reason: {0}", e);
}
Console.WriteLine("Files successfully deleted");
}
return count;
}
public static DateTime GetRelativeDateTime(int days, int hours, int minutes)
{
return DateTime.Now.AddDays(-days).AddHours(-hours).AddMinutes(-minutes);
}
public static ArrayList FilesOlderThan(DateTime dt, string filter)
{
DirectoryInfo directory = new DirectoryInfo(Directory.GetCurrentDirectory());
FileInfo[] files = directory.GetFiles(filter); //get FileInfos for the files in the current directory matching the filter expression
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
}
return older;
}
}
}
[code]
button event handler that deletes files.. -
private void DeleteFiles_Click(object sender, EventArgs e)
-
{
-
FolderWatcher fw = new FolderWatcher();
-
fw.FolderPath = @"c:\csharp"; // FolderName
-
fw.DeleteFilesOlderThan(0, 0, 0, "*.txt"); // deletes everything older than specified days,hrs, and mins respectively
-
}
-
And you keep getting the exceptions printed out?
nopes, I am not getting any exceptions printed out
Have you put a breakpoint on the File.Delete() to see if
A) it's actually getting called
and
B) What value is being passed to it?
okay i will check that out.......i want to know another thing. I wrote the following code to create text files and to create multiple text files i guess i can run the code in a loop. but i want to generate dummy files using .txt, .log, .exe file format in button GenerateTestFiles eventhandler -
using System;
-
using System.IO;
-
-
class FileTest
-
{
-
static void Main()
-
{
-
StreamWriter outStream = null;
-
string filename = "output.txt";
-
-
try
-
{
-
outStream = new StreamWriter(filename);
-
outStream.WriteLine("Hello World");
-
outStream.Close();
-
}
-
catch (Exception e)
-
{
-
Console.WriteLine("Unable to create file {0}", filename);
-
Console.WriteLine("Reason: {0}", e);
-
return;
-
}
-
Console.WriteLine("File successfully created");
-
}
-
}
-
I created three textboxes to enter days, mins, hrs and a combo box for extension on my form.
this wouldn't work? -
private void DeleteFiles_Click(object sender, EventArgs e)
-
{
-
FolderWatcher fw = new FolderWatcher();
-
fw.FolderPath = @"c:\csharp"; // FolderName
-
OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
-
fw.DeleteFilesOlderThan(int.Parse(Textbox1.Text), int.Parse(Textbox2.Text), int.Parse(Textbox3.Text), OpenFileDialog1.Filter); // deletes everything older than specified days,hrs, and mins respectively
-
}
-
It might or it might not, did you go in and check to see if it even found any files that matched the search pattern?
i put a breakpoint to check it throughly. this is the FolderWatcher.cs class. I modified the code using DateTime object. I think FolderPath is not defined in the current directory -
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));
-
//}
-
-
public int DeleteFilesOlderThan(int Days, int Hrs, int Mins, string filter)
-
{
-
DateTime dt = GetRelativeDateTime(Days, Hrs, Mins);
-
ArrayList oldFilePaths = FilesOlderThan(dt, filter);
-
int count = 0;
-
foreach (string filePath in oldFilePaths)
-
{
-
try
-
{
-
File.Delete(filePath);
-
count++;
-
}
-
catch (Exception e)
-
{
-
Console.WriteLine("Unable to delete {0}", filePath);
-
Console.WriteLine("Reason: {0}", e);
-
}
-
Console.WriteLine("Files successfully deleted");
-
}
-
return count;
-
}
-
-
public static DateTime GetRelativeDateTime(int days, int hours, int minutes)
-
{
-
return DateTime.Now.AddDays(-days).AddHours(-hours).AddMinutes(-minutes);
-
}
-
-
public static ArrayList FilesOlderThan(DateTime dt, string filter)
-
{
-
DirectoryInfo directory = new DirectoryInfo(Directory.GetCurrentDirectory());
-
FileInfo[] files = directory.GetFiles(filter); //get FileInfos for the files in the current directory matching the filter expression
-
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
-
}
-
-
return older;
-
}
-
}
-
}
-
Sign in to post your reply or Sign up for a free account.
Similar topics
by: Master of C++ |
last post by:
Hi,
I am an absolute newbie to Exception Handling, and I am trying to
retrofit exception handling to a LOT of C++ code that I've written
earlier. I am just looking for a bare-bones, low-tech...
|
by: bj7lewis |
last post by:
I am working on a project I want to add a few files as resource to
access(copy them to FS and use) at runtime.
So far in VS.NET IDE, I Add Files to the project and set its Build Action to...
|
by: John |
last post by:
Hi
I have this problem on winxp/offixexp machine but not on win2k/office2k
machines.
I have a main form which has a panel which has a child form. The child form
opens a dialog form. When the...
|
by: Bob |
last post by:
Say I have two app domains, Domain A and Domain B, that I do not want to
pass object references between. Domain A has Assembly A loaded, which
contains a type that inherits from exception. I want...
|
by: Dean Slindee |
last post by:
I have a exception handling class that could be called from either a windows
project app or a console project app. Is there any way for this class to
determine which type of app called it without...
|
by: Richard Myers |
last post by:
Hello,
I was recently asked how to ensure an app falls over when an exception
occurs that has not been caught.
The framework will often prompt the user to Quit or continue in such case
and...
|
by: Susan Baker |
last post by:
Hi,
I am writing a Win32 DLL. I want to be able to handle any SEGVs
(segmentation violations) gracefully, by using an error handler of sorts.
Currently, if a user of my DLL (typically a VB...
|
by: maciek |
last post by:
Hi,
I was wondering if anyone could suggest me a book/article/tutorial on
Exception Handling in multi tier Windows Apps. What are the best
practices/ways to implement EH in multi tier...
|
by: John Wright |
last post by:
I am running a console application that connects to an Access database (8
million rows) and converts it to a text file and then cleans and compacts
the database. When it runs I get the following...
|
by: =?Utf-8?B?YW5rMmdv?= |
last post by:
Hi,
Thanks in advance for reading this.
Not sure where to post this question, but I hope someone in here can help.
Trying to write to Event Log in VS 2005 (.NET 2.0) using Enterprise Library...
|
by: taylorcarr |
last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: ryjfgjl |
last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
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: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
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: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
| |