上面的代码请添加异常抛出功能
时间: 2024-02-20 16:57:54 浏览: 54
抛出异常代码示例
好的,以下是添加异常抛出功能后的代码:
```csharp
using System;
using System.IO;
using System.Timers;
class Program
{
static void Main(string[] args)
{
try
{
Timer timer = new Timer(60000); // 60,000 milliseconds = 1 minute
timer.Elapsed += OnTimedEvent;
timer.AutoReset = true;
timer.Enabled = true;
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
try
{
string folderPath = @"C:\example\folder"; // Replace with your folder path
DateTime sevenDaysAgo = DateTime.Now.AddDays(-7);
DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
FileInfo[] files = directoryInfo.GetFiles();
foreach (FileInfo file in files)
{
if (file.CreationTime < sevenDaysAgo)
{
file.Delete();
}
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred while deleting files: {ex.Message}");
}
}
}
```
在 `Main` 方法中,我们将整个程序包裹在一个 try-catch 块中,以便捕获可能出现的异常。在 `OnTimedEvent` 方法中,我们也添加了一个 try-catch 块,以便在删除文件时捕获异常。在每个 catch 块中,我们使用 `Console.WriteLine` 输出错误消息。这样就可以更好地处理程序中的异常了。
阅读全文