I have a windows service which needs to monitor a directory for files and then move it to another directory. I am using a FileSystemWatcher to implement this.
This is my main Service class.
public partial class SqlProcessService : ServiceBase
{
public SqlProcessService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
FileProcesser fp = new FileProcesser(ConfigurationManager.AppSettings["FromPath"]);
fp.Watch();
}
protected override void OnStop()
{
}
}
This is my FileProcessor Class
public class FileProcesser
{
FileSystemWatcher watcher;
string directoryToWatch;
public FileProcesser(string path)
{
this.watcher = new FileSystemWatcher();
this.directoryToWatch = path;
}
public void Watch()
{
watcher.Path = directoryToWatch;
watcher.NotifyFilter = NotifyFilters.LastAccess |
NotifyFilters.LastWrite |
NotifyFilters.FileName |
NotifyFilters.DirectoryName;
watcher.Filter = "*.*";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
private void OnChanged(object sender, FileSystemEventArgs e)
{
File.Copy(e.FullPath, ConfigurationManager.AppSettings["ToPath"]+"\\"+Path.GetFileName(e.FullPath),true);
File.Delete(e.FullPath);
}
}
After I install and start the service, it works fine for 1 file and then stops automatically. What is making the service stop automatically? When I check the event log I don't see an error or warning!
The FileSystemWatcher class is a very powerful tool that's been a part of the Microsoft . NET Framework since version 1.1, and according to its official definition (bit.ly/2b8iOvQ), it “listens to the file system change notifications and raises events when a directory, or file in a directory, changes.”
Nope, filesystemwatchers run on their own thread.
Use FileSystemWatcher to watch for changes in a specified directory. You can watch for changes in files and subdirectories of the specified directory. You can create a component to watch files on a local computer, a network drive, or a remote computer.
The FileSystemWatcher lets you detect several types of changes in a directory or file, like the 'LastWrite' date and time, changes in the size of files or directories etc. It also helps you detect if a file or directory is deleted, renamed or created.
Your local variable fp get disposed off once it goes out of scope. The solution is to declare it as an instance variable instead
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With