views:

88

answers:

4

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 recommended 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?

+1  A: 

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.

Reed Copsey
If I want to use the registry and I try to use HKEY_LOCAL_MACHINE, will Vista/Win7 complain?
wizlb
It should work from a service, since you (most likely) have permissions to read and write to HKLM.
Reed Copsey
A: 

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.

TheObjectGuy
A: 

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.

Zack Elan
A: 

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?

Anders Fjeldstad