我正在尝试在 C# 中创建监视文件夹应用程序,它将在新文件到达时执行操作。由于监视的文件夹位于 GPFS 共享上,因此我无法使用 FileSystemWatcher(在 NTFS 中对我来说很好用)。因此,我将该应用程序基于其他同事解决方案。该应用程序很好地显示了“计时器启动”消息,但是当涉及到
timer.Elapsed += new System.Timers.ElapsedEventHandler(DoStuff);
它没有调用 DoStuff 方法——“开始新文件过程”消息永远不会出现。我做错了什么?这是完整的代码:
namespace MonitorFolderActivity
{
public partial class frmMain : Form
{
List<string> fileList = new List<string>();
System.Timers.Timer timer;
DateTime LastChecked;
public frmMain()
{
InitializeComponent();
}
private void abortAcitivityMonitoring()
{
btnStart_Stop.Text = "Start";
txtActivity.Focus();
}
private void startActivityMonitoring(string sPath)
{
if (sPath.Length < 3)
{
MessageBox.Show("You have to enter a folder to monitor.",
"Hey..!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
abortAcitivityMonitoring();
}
else
{
TS_AddLogText(string.Format("Timer starts\r\n"));
timer = new System.Timers.Timer();
timer.AutoReset = false;
timer.Elapsed += new System.Timers.ElapsedEventHandler(DoStuff);
}
}
private void stopActivityMonitoring()
{
TS_AddLogText(string.Format("Timer stops\r\n"));
this.timer.Stop();
}
private void DoStuff(object sender, System.Timers.ElapsedEventArgs e)
{
TS_AddLogText(string.Format("Starting new files proc\r\n"));
LastChecked = DateTime.Now;
string[] files = System.IO.Directory.GetFiles("D:\\MEDIAIN\\", "*", System.IO.SearchOption.AllDirectories);
foreach (string file in files)
{
if (!fileList.Contains(file))
{
fileList.Add(file);
TS_AddLogText(string.Format(file));
}
}
TimeSpan ts = DateTime.Now.Subtract(LastChecked);
TimeSpan MaxWaitTime = TimeSpan.FromMinutes(1);
if (MaxWaitTime.Subtract(ts).CompareTo(TimeSpan.Zero) > -1)
timer.Interval = MaxWaitTime.Subtract(ts).TotalMilliseconds;
else
timer.Interval = 1;
timer.Start();
}
private delegate void AddLogText(string text);
private void TS_AddLogText(string text)
{
if (this.InvokeRequired)
{
AddLogText del = new AddLogText(TS_AddLogText);
Invoke(del, text);
}
else
{
txtActivity.Text += text;
}
}
private void btnStart_Stop_Click(object sender, EventArgs e)
{
if (btnStart_Stop.Text.Equals("Start"))
{
btnStart_Stop.Text = "Stop";
startActivityMonitoring(txtFolderPath.Text);
}
else
{
btnStart_Stop.Text = "Start";
stopActivityMonitoring();
}
}
private void lblActivity_Click(object sender, EventArgs e)
{
}
private void lblToMonitor_Click(object sender, EventArgs e)
{
}
}
}