Hi All,
I can't find any good examples of throwing exceptions. I have the following code. I want to include all the possible exceptions i can. Help me out on this. I am just moving away from console object and moving towards exception object.
I can't find any good examples of throwing exceptions. I have the following code. I want to include all the possible exceptions i can. Help me out on this. I am just moving away from console object and moving towards exception object.
Code:
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;
string message = null;
foreach (string filePath in oldFilePaths)
{
try
{
File.Delete(filePath);
count++;
}
catch (FileNotFoundException e)
{
}
catch (DirectoryNotFoundException e)
{
}
catch (Exception e)
{
message = "Unable to delete " + filePath + "\r\n";
message += String.Format("Reason: {0}", e.Message);
MessageBox.Show(message);
// Error..Property or indexer 'System.Exception.Message' cannot be assigned to--it is read only
//e.Message = "Unable to delete " + filePath + e.ToString();
//Console.WriteLine("Unable to delete " + filePath);
//Console.WriteLine("Reason: {0} ", e);
}
//message = ("Files successfully deleted");
//MessageBox.Show(message);
//message = String.Format("{0} ex {1} files successfully deleted", count, oldFilePaths.Count);
//MessageBox.Show(message);
//return count;
}
return count;
}
// Using GetRelativeDateTime as a private method instead of public however as it is only to be used internally
private static DateTime GetRelativeDateTime(int days, int hours, int minutes)
{
return DateTime.Now.AddDays(-days).AddHours(-hours).AddMinutes(-minutes);
}
public ArrayList FilesOlderThan(DateTime dt, string filter)
{
//m_FolderPath = @"C:\CsharpTempFolder";
// Using the supplied path
//DirectoryInfo directory = new DirectoryInfo(Directory.GetCurrentDirectory())
DirectoryInfo directory = new DirectoryInfo(m_FolderPath);
// Filter is applied to the directory.GetFiles method to get files of given extension
// get FileInfos for the files in the current directory matching the filter expression
FileInfo[] files = directory.GetFiles(filter);
//list to hold the result
ArrayList older = new ArrayList();
foreach (FileInfo file in files)
{
//if smaller (older) than the relative time
if (file.CreationTime < dt)
older.Add(file.FullName); //add it to the list
}
return older;
}
Comment