How do I best monitor a selected folder (and subfolder) for changes?

  • Thread starter Thread starter Egil Hansen
  • Start date Start date
E

Egil Hansen

Hi all

Do C# and .net have some way to monitor a folder in Windows XP/Windows
2000. I want to mirror the content of the folder, including subfolders
(if any exsists) to another place, and I want to mirror the changes as
they happen.
 
The below code monitors for xml file, you could modify and use it how u need
it

fsWatcher = new System.IO.FileSystemWatcher(strDirectoryName);
fsWatcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
fsWatcher.Filter = "*.xml";
fsWatcher.Created += new FileSystemEventHandler(OnNewFileAdded);
fsWatcher.Changed += new FileSystemEventHandler(OnFileChanged);
fsWatcher.EnableRaisingEvents = true;

public void OnNewFileAdded(object source, FileSystemEventArgs e)
{
//Your code
}

public void OnFileChanged(object source, FileSystemEventArgs e)
{
//Your code
}
 
Hi Egil
You can use classes of the .net to list the directory info get the folder
info ( of all files with in it . then you can save that info somewhere (
may be save the file names as strings and write them on a text file) . then
periodaclly check your folder and compare for changing
This snippet of code list content of directory in a tree view
tn = new TreeNode(@"C:\");
tn.Tag="1";

tvFileSystem.Nodes.Add(tn);
DirectoryInfo d = new DirectoryInfo("C:\\");
DirectoryInfo[] dd= d.GetDirectories();
FileInfo[] fn = d.GetFiles();
foreach (DirectoryInfo myD in dd) {
TreeNode myTree = new TreeNode(myD.Name);
myTree.Nodes.Add(new TreeNode("unexplored"));
myTree.Tag="0";

tn.Nodes.Add(myTree);
}
foreach (FileInfo myF in fn)
{
tn.Nodes.Add(new TreeNode(myF.Name));
}
tvFileSystem.Update();
tvFileSystem.Visible=true;

you might need to write your application as a windows service if you want
this check to be running at all time.

Mohamed Mahfouz
MEA Developer Support Center
ITworx on behalf of Microsoft EMEA GTSC
 
Use the FileSystemWatcher class. This only monitors a single folder, so you
will have to find the subfolders and monitor them manually to see if their
contents change. Directory.GetDirectories will give you a list of
subfolders.

--Liam.
 
Back
Top