请用c#写一个定时删除指定文件夹的服务,指定文件夹可使用配置文件配置
以下是一个示例代码,实现了每隔一段时间删除指定文件夹下的所有文件。
首先需要创建一个Windows服务,然后在服务中添加Timer控件和FileSystemWatcher控件。
Timer控件用于定时执行删除任务,而FileSystemWatcher控件用于监控指定的文件夹,以便在有新文件添加时及时删除。
代码如下:
using System; using System.IO; using System.ServiceProcess; using System.Timers; using System.Configuration;
namespace DeleteFolderService { public partial class Service1 : ServiceBase { private Timer timer;
private string folderPath;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
// 读取配置文件中指定的文件夹路径
folderPath = ConfigurationManager.AppSettings["FolderPath"];
// 初始化Timer控件
timer = new Timer();
timer.Interval = 60000; // 每分钟执行一次
timer.Elapsed += new ElapsedEventHandler(OnTimer);
timer.Start();
// 初始化FileSystemWatcher控件
FileSystemWatcher watcher = new FileSystemWatcher(folderPath);
watcher.Created += new FileSystemEventHandler(OnFileCreated);
watcher.EnableRaisingEvents = true;
}
protected override void OnStop()
{
timer.Stop();
timer.Dispose();
}
private void OnTimer(object source, ElapsedEventArgs e)
{
// 删除文件夹下的所有文件
DirectoryInfo di = new DirectoryInfo(folderPath);
foreach (FileInfo file in di.GetFiles())
{
try
{
file.Delete();
}
catch (Exception ex)
{
// 记录异常信息
}
}
}
private void OnFileCreated(object sender, FileSystemEventArgs e)
{
// 文件添加时立即删除
try
{
File.Delete(e.FullPath);
}
catch (Exception ex)
{
// 记录异常信息
}
}
}
}
需要在App.config文件中添加以下配置:
其中FolderPath为指定的文件夹路径。
原文地址: https://www.cveoy.top/t/topic/AXf 著作权归作者所有。请勿转载和采集!