473,386 Members | 1,785 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,386 software developers and data experts.

C# App: Exception Handling

Hi All,

Is it the right way of handling exception in a method?

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 5 '07 #1
13 1678
Plater
7,872 Expert 4TB
That looks like a pretty solid handling to me.
Dec 5 '07 #2
Thanks, But when i debug the application, the files get deleted but i dont see the msg showing Files successfully deleted.
Dec 5 '07 #3
can you check if this is coded properly 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 int DeleteFilesOlderThan(DateTime dt)
  7.         {
  8.             string[] older = FilesOlderThan(dt);
  9.             int count = 0;
  10.             foreach (string file in files)
  11.             {
  12.                 try
  13.                 {
  14.                     File.Delete(file.Name);
  15.                     count++;
  16.                 }
  17.                 catch (Exception e)
  18.                 {
  19.                     Console.WriteLine("Unable to delete " + file);
  20.                     Console.WriteLine("Reason: {0}", e);
  21.                     //Console.WriteLine("Detected an exception!!!\n" + e );
  22.                 }
  23.                 Console.WriteLine("Files successfully deleted");
  24.             }
  25.             // presumably number of files deleted to be returned
  26.             return count;
  27.         }
  28.  
  29.         public static string[] FilesOlderThan(DateTime dt)
  30.         {
  31.             DirectoryInfo directory = new DirectoryInfo(Directory.GetCurrentDirectory());
  32.             FileInfo[] files = directory.GetFiles(FolderPath); //get FileInfos for the files in the current directory 
  33.             ArrayList older = new ArrayList(); //list to hold the result 
  34.             foreach (FileInfo file in files)
  35.             {
  36.                 if (file.CreationTime < dt) //if smaller (older) than the relative time 
  37.                     older.Add(file.Name); //add it to the list 
  38.             }
  39.         }
  40.  
Dec 5 '07 #4
Plater
7,872 Expert 4TB
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?
Dec 5 '07 #5
Before when i was compiling the application, it was showing in pending checkins that files successfully deleted. but not anymore:S
Dec 5 '07 #6
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..
Expand|Select|Wrap|Line Numbers
  1.         private void DeleteFiles_Click(object sender, EventArgs e)
  2.         {
  3.             FolderWatcher fw = new FolderWatcher();
  4.             fw.FolderPath = @"c:\csharp"; // FolderName
  5.             fw.DeleteFilesOlderThan(0, 0, 0, "*.txt"); // deletes everything older than specified days,hrs, and mins respectively 
  6.         }
  7.  
Dec 5 '07 #7
Plater
7,872 Expert 4TB
And you keep getting the exceptions printed out?
Dec 5 '07 #8
nopes, I am not getting any exceptions printed out
Dec 5 '07 #9
Plater
7,872 Expert 4TB
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?
Dec 6 '07 #10
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

Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.IO;
  3.  
  4. class FileTest
  5. {
  6.     static void Main()
  7.     {
  8.         StreamWriter outStream = null;
  9.         string filename = "output.txt";
  10.  
  11.         try
  12.         {
  13.             outStream = new StreamWriter(filename);
  14.             outStream.WriteLine("Hello World");
  15.             outStream.Close();
  16.         }
  17.         catch (Exception e)
  18.         {
  19.             Console.WriteLine("Unable to create file {0}", filename);
  20.             Console.WriteLine("Reason: {0}", e);
  21.             return;
  22.         }
  23.         Console.WriteLine("File successfully created");
  24.     }
  25. }
  26.  
Dec 6 '07 #11
I created three textboxes to enter days, mins, hrs and a combo box for extension on my form.

this wouldn't work?
Expand|Select|Wrap|Line Numbers
  1.         private void DeleteFiles_Click(object sender, EventArgs e)
  2.         {
  3.             FolderWatcher fw = new FolderWatcher();
  4.             fw.FolderPath = @"c:\csharp"; // FolderName
  5.             OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
  6.             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 
  7.         }
  8.  
Dec 6 '07 #12
Plater
7,872 Expert 4TB
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?
Dec 6 '07 #13
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
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.         public int DeleteFilesOlderThan(int Days, int Hrs, int Mins, string filter)
  91.         {
  92.             DateTime dt = GetRelativeDateTime(Days, Hrs, Mins);
  93.             ArrayList oldFilePaths = FilesOlderThan(dt, filter);
  94.             int count = 0;
  95.             foreach (string filePath in oldFilePaths)
  96.             {
  97.                 try
  98.                 {
  99.                     File.Delete(filePath);
  100.                     count++;
  101.                 }
  102.                 catch (Exception e)
  103.                 {
  104.                     Console.WriteLine("Unable to delete {0}", filePath);
  105.                     Console.WriteLine("Reason: {0}", e);
  106.                 }
  107.                 Console.WriteLine("Files successfully deleted");
  108.             }
  109.             return count;
  110.         }
  111.  
  112.         public static DateTime GetRelativeDateTime(int days, int hours, int minutes)
  113.         {
  114.             return DateTime.Now.AddDays(-days).AddHours(-hours).AddMinutes(-minutes);
  115.         }
  116.  
  117.         public static ArrayList FilesOlderThan(DateTime dt, string filter)
  118.         {
  119.             DirectoryInfo directory = new DirectoryInfo(Directory.GetCurrentDirectory());
  120.             FileInfo[] files = directory.GetFiles(filter); //get FileInfos for the files in the current directory matching the filter expression
  121.             ArrayList older = new ArrayList(); //list to hold the result 
  122.             foreach (FileInfo file in files)
  123.             {
  124.                 if (file.CreationTime < dt) //if smaller (older) than the relative time 
  125.                     older.Add(file.Name); //add it to the list 
  126.             }
  127.  
  128.             return older;
  129.         }
  130.     }
  131. }
  132.  
Dec 6 '07 #14

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

Similar topics

3
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...
12
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...
0
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...
2
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...
3
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...
5
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...
2
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...
1
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...
1
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...
0
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...
0
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,...
0
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$) { } ...
0
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...
0
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...
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
jinu1996
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...

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.