Pablo Costa
Pablo Costa

Reputation: 125

When/where to implement FileSystemWatcher

I've a code (program) working by now, that the uses select input files, outputfolders and then convert to xml.

All variables and methods are inside a class (another file, but this is no problem).

Anyway. I would like to change its behaviour to a hotfolder behaviour ; that way, when some file is added to the folder it'll process based on already implemented methods and do whatever stuff i want.

Okay, so now here comes my question: actually , on Form1.cs all i got is some button_click calls. Should i place the FileSystemWatcher + OnChanged method inside Form1.Cs or should i place it inside my Classes.cs file (this is the file with all methods, variables, etc - the business logic). Also, when do i call it ? As soon the form1 is initialized would be best ? Thanks for any opinion :)

Upvotes: 0

Views: 613

Answers (1)

Alberto Chiesa
Alberto Chiesa

Reputation: 7350

For sure, do not put the Watcher in your form.

A pattern you can use is something like this:

public class DirectoryRefresher : IDisposable
{
    private FileSystemWatcher FileWatcher { get; set; }

    public DirectoryRefresher(string directorypath)
    {
        FileWatcher = SetupFileWatcher(directoryPath);
    }

    protected FileSystemWatcher SetupFileWatcher(string path)
    {
        var watcher = new FileSystemWatcher(path);

        watcher.Changed += (sender, e) => { DoYourProcessing(e.FullPath); };
        watcher.Created += (sender, e) => { DoYourProcessing(e.FullPath); };
        watcher.Deleted += (sender, e) => { DoYourProcessing(e.FullPath); };

        watcher.EnableRaisingEvents = true;

        return watcher;
    }

    public void DoYourProcessing(string filePath)
    {
        ...
    }

    public void Dispose()
    {
        try
        {
            if (FileWatcher != null)
            {
                FileWatcher.Dispose();
                FileWatcher = null;
            }
        }
        catch
        {
            // ignored
        }
    }

}

When you know the folder, you just instantiate a DirectoryRefresher. When you want to stop it, you just Dispose() it.

Upvotes: 3

Related Questions