Search code examples
c#winformsfilesystemwatcher

Using pre-defined string for "Path" attribute in FileSystemWatcher


I'm making a simple winforms application in C#, with VS2010. My winforms design contains a FileSystemWatcher, which fires a pile of code when a file is created.

My problem is that the path for FileSystemWatcher needs to be defined prior to the program running, as it won't always be the same.

I have a string called startPath which I'd like to use, but it would appear that I can't just add this to the "path" field in the FileSystemWatcher properties in my design.

I was able to get it to work if I edited my form1.designer.cs, but as I swiftly learned this code is regenerated even if a different component of the form is edited!

As you might have guessed, I'm still very much learning C#.net (about a week in), and am by no means experienced! If I'm missing something stupid, please point it out!


Solution

  • The FileSystemWatcher has a path property that can be used to change the path after the FileSystemWatcher object is initialized. Otherwise, you'll have to re-setup your watcher if you use the constructor to set the path to watch.

    FileSystemWatcher.Path Property

    Storing the path itself can be easily done through the Application Settings as mentioned by @leppie

    Reference for settings:
    Application Settings Overview
    Using Settings in C#
    Saving User Settings in Winform Application