Recommended place for Windows Service state storage?
I have a Windows Service written in C# (.Net 3.5) and I need to store some state somewhere so that next time the service starts up, it knows where it left off.
What is the r开发者_如何学编程ecommended store for this type of thing? The registry? What if I just put some user settings in a Settings.settings file? Where would the user profile be for a service executing as LocalSystem or NetworkService?
Personally, I prefer the registry for server state storage, provided it isn't a large amount of information.
If you're storing a large amount of information, a local database is another option. Services have the advantage of running under elevated privelidges, so you can typically use local file storage, as well.
I would go with a .settings file, since its properties are type safe. This is of course assuming that the service is not going to store a large amount of information. Does it really matter where the system chooses to store the settings file?
I hate to say this, but the best answer is that it depends. Without knowing the purpose of your service, a correct answer can't be given. Having said that... the world is your oyster, so to speak.
If it's a small, fairly simple chunk of data, you can create an XML serializable class and very easily write it to disk on shutdown and read it back on startup. For a simple enough class, you can just add the [Serializable] attribute, and the XmlSerializer will automatically know how to serialize/deserialize it.
If you have enough data that a SQL database would be a better fit, look into SQL Server Compact Edition or the System.Data.SQLite binding for SQLite.
Both will let you create a database as a single file, without having to install any extra Windows services or configure anything. System.Data.SQLite doesn't even need to be installed - it's contained entirely with the .dll that your project references.
In either case, the best location for the file is probably SpecialFolder.CommonApplicationData - I think this ends up being C:\ProgramData\ on Vista, but avoids having to hardcode the exact path.
精彩评论