In the VS2005,. NET has a FileSystemWatcher control, used to monitor file changes, it will notify the file creation, modification, delete the message. There are a lot of examples on the Internet, but in practical application, I found some problems to be solved, I made a simple demo to solve the following problems:
1. Multiple consecutive triggers (solved by a timer)
2. Able to monitor the network path (ServiceProcessInstaller account attribute set to NetworkService)
3. Through the Windows service to achieve, make installation files to facilitate registration services
Precautions:
1. Remember that the network path to the permissions of the guest, otherwise monitoring can not.
2. Modify the Watcher.path in the Service1 code.
3. Create a new file C:\test.log, set this file to writable permissions.
4. Manually start the service after the installation is complete.
Key code:
public class AdvancedFileSystemWatcher:System.IO.FileSystemWatcher
{
public event Networkpathunavailableeventhandler Networkpathunavailable;
public delegate void Networkpathunavailableeventhandler (String message);
public event Networkpathavailableeventhandler Networkpathavailable;
public delegate void Networkpathavailableeventhandler (String message);
Private System.Timers.Timer _mytimer = new System.Timers.Timer ();
private bool _isnetworkunavailable = false;
Public Advancedfilesystemwatcher ()
{
_mytimer.start ();
}
Public advancedfilesystemwatcher (int inetworkwatchinterval)
{
if (Inetworkwatchinterval > 0)
{
_mytimer.interval = Inetworkwatchinterval;
}
Else
{
_mytimer.interval = 2000;
}
_mytimer.start ();
}
public void Close ()
{
_mytimer.stop ();
_mytimer.dispose ();
}
private void _mytimer_elapsed (object sender, System.Timers.ElapsedEventArgs e)
{
DirectoryInfo MyFolder;
Try
{
MyFolder = new DirectoryInfo (base. Path);
if (!_isnetworkunavailable)
{
if (!myfolder.exists)
{
_isnetworkunavailable = true;
if (networkpathunavailable!= null)
{
Networkpathunavailable ("A network error has occured or the path does not exist anymore");
}
}
}
Else
{
if (myfolder.exists)
{
_isnetworkunavailable = false;
if (networkpathavailable!= null)
{
Networkpathavailable ("The network or path has been restored");
}
}
}
}
catch (Exception ex)
{
Throw
}
Finally
{
MyFolder = null;
}
}
}
SOURCE Download: Http://files.cnblogs.com/binbin1845/FileWatchServiceTest.rar