Introduction
This code will show how to monitor multiple files by creating multiple instances of FileSystemWatcher
.
Using the code
To use the code, the following namespaces must be referenced:
using System.IO;
using System.Collections;
System.IO
will be used for FileSystemWatcher
and Directory
, while System.Collections
for the ArrayList
. Now to the code:
namespace MonitorFolderActivity
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnRun_Click(object sender, EventArgs e)
{
DisableButtons();
bool bMonitorUpdated = chkMonitorUpdated.Checked;
bool bMonitorDeleted = chkMonitorDeleted.Checked;
bool bMonitorCreated = chkMonitorCreated.Checked;
ArrayList aFileWatcherInstance = new ArrayList();
foreach (string sMonitorFolder in lstFolders.Items)
{
if (Directory.Exists(sMonitorFolder))
{
FileSystemWatcher oFileWatcher = new FileSystemWatcher();
oFileWatcher.Path = sMonitorFolder;
oFileWatcher.Filter = txtMonitorFileExpression.Text;
if (bMonitorUpdated)
oFileWatcher.Changed +=
new System.IO.FileSystemEventHandler(FileSystemWatcherUpdated);
else
oFileWatcher.Changed -=
new System.IO.FileSystemEventHandler(FileSystemWatcherUpdated);
if (bMonitorDeleted)
oFileWatcher.Deleted +=
new System.IO.FileSystemEventHandler(FileSystemWatcherDeleted);
else
oFileWatcher.Deleted -=
new System.IO.FileSystemEventHandler(FileSystemWatcherDeleted);
if (bMonitorCreated)
oFileWatcher.Created +=
new System.IO.FileSystemEventHandler(FileSystemWatcherCreated);
else
oFileWatcher.Created -=
new System.IO.FileSystemEventHandler(FileSystemWatcherCreated);
oFileWatcher.EnableRaisingEvents = true;
aFileWatcherInstance.Add(oFileWatcher);
}
}
}
void FileSystemWatcherCreated(object sender, System.IO.FileSystemEventArgs e)
{
string sLog = "File Created: " + e.Name;
AppendText(sLog);
}
void FileSystemWatcherDeleted(object sender, System.IO.FileSystemEventArgs e)
{
string sLog = "File Deleted: " + e.Name;
AppendText(sLog);
}
void FileSystemWatcherUpdated(object sender, System.IO.FileSystemEventArgs e)
{
string sLog = "File Updated: " + e.Name;
AppendText(sLog);
}
private delegate void AppendListHandler(string sLog);
private void AppendText(string sLog)
{
if (lstResultLog.InvokeRequired)
lstResultLog.Invoke(new AppendListHandler(AppendText),
new object[] { sLog });
else
lstResultLog.Items.Add(Convert.ToString(DateTime.Now) +
" - " + sLog);
}
private void DisableButtons()
{
chkMonitorUpdated.Enabled = false;
chkMonitorDeleted.Enabled = false;
chkMonitorCreated.Enabled = false;
txtMonitorFileExpression.Enabled = false;
btnRun.Enabled = false;
}
}
}