Search code examples
c#.netwinformsstartupfilesystemwatcher

Filesystemwatcher C# watcher objects persist on startup


Following this tutorial: http://www.codeproject.com/Articles/26528/C-Application-to-Watch-a-File-or-Directory-using-F

I've modified the above tutorial and created a windows form application that can create multiple filesystemwatcher instances and track/delete them in a list on the form.

My next goal is to make it so that on computer restart/startup, the windows form application will remain active as well as all the watcher objects I've created.

I figure that this would take 4 parts:
1) Save information on watcher objects and their metadata to be accessed after restart (currently I save references to all watcher objects in a List variable)
2) Have the watcher objects persist even after restart
3) Start the windows form on startup
4) Access the saved watcher object information so that it still appears on the windows form list.

I am new to C# and this is my first project, so I have little idea on how to tackle these steps. Any help would be appreciated.


Solution

  • You have to create new watcher objects after restart. The information you need to store needs to have a different class, e.g.:

    public class SettingItem
    {
      public string Path { get; set; }
    }
    public class Settings
    {
        public SettingItem[] Items { get; set; }
    }
    

    Then you can use XmlSerializer to store the objects on disk:

    public static class SettingManager
    {
        public static void Save(string path, object obj)
        {
            if (string.IsNullOrWhiteSpace(path))
                throw new ArgumentNullException(nameof(path));
            if (obj == null)
                throw new ArgumentNullException(nameof(obj));
    
            Directory.CreateDirectory(Path.GetDirectoryName(path));
    
            using (var s = new StreamWriter(path))
            {
                var xmlSerializer = new XmlSerializer(obj.GetType());
                xmlSerializer.Serialize(s, obj);
            }
        }
    
        public static T Load<T>(string path) where T : class, new()
        {
            if (string.IsNullOrWhiteSpace(path))
                throw new ArgumentNullException(nameof(path));
    
            if (File.Exists(path))
            {
                using (var s = new StreamReader(path))
                {
                    var xmlSerializer = new XmlSerializer(typeof(T));
                    return xmlSerializer.Deserialize(s) as T;
                }
            }
            return new T();
        }
    }
    

    Usage:

    var settingPath = @"c:\...xml";
    
    var settings0 = new Settings
    {
        Items = new[]
        {
            new SettingItem { Path = @"c:\path\to\watch" },
        }
    };
    SettingManager.Save(settingPath, settings0);
    
    var settings1 = SettingManager.Load<Settings>(settingPath);