.net - Filesystemwatcher C# watcher objects persist on startup -
following tutorial: http://www.codeproject.com/articles/26528/c-application-to-watch-a-file-or-directory-using-f
i've modified above tutorial , created windows form application can create multiple filesystemwatcher instances , track/delete them in list on form.
my next goal make on computer restart/startup, windows form application remain active watcher objects i've created.
i figure take 4 parts:
1) save information on watcher objects , metadata accessed after restart (currently save references watcher objects in list variable)
2) have watcher objects persist after restart
3) start windows form on startup
4) access saved watcher object information still appears on windows form list.
i new c# , first project, have little idea on how tackle these steps. appreciated.
you have create new watcher objects after restart. information need store needs have different class, e.g.:
public class settingitem { public string path { get; set; } } public class settings { public settingitem[] items { get; set; } }
then can use xmlserializer
store 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) 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) 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);
Comments
Post a Comment