What I want to achieve is very simple: I have a Windows Forms (.NET 3.5) application that uses a path for reading information. This path can be modified by the user, by using the options form I provide.
Now, I want to save the path value to a file for later use. This would be one of the many settings saved to this file. This file would sit directly in the application folder.
I understand three options are available:
- ConfigurationSettings file (appname.exe.config)
- Registry
- Custom XML file
I read that the .NET configuration file is not foreseen for saving values back to it. As for the registry, I would like to get as far away from it as possible.
Does this mean that I should use a custom XML file to save configuration settings? If so, I would like to see code example of that (C#).
I have seen other discussions on this subject, but it is still not clear to me.
The registry is a no-go. You're not sure whether the user which uses your application, has sufficient rights to write to the registry.
You can use the
app.config
file to save application-level settings (that are the same for each user who uses your application).I would store user-specific settings in an XML file, which would be saved in Isolated Storage or in the SpecialFolder.ApplicationData directory.
Next to that, as from .NET 2.0, it is possible to store values back to the
app.config
file.The
ApplicationSettings
class doesn't support saving settings to the app.config file. That's very much by design, apps that run with a properly secured user account (think Vista UAC) do not have write access to the program's installation folder.You can fight the system with the
ConfigurationManager
class. But the trivial workaround is to go into the Settings designer and change the setting's scope to User. If that causes hardships (say, the setting is relevant to every user), you should put your Options feature in a separate program so you can ask for the privilege elevation prompt. Or forego using a setting.As far as I can tell, .NET does support persisting settings using the built-in application settings facility:
If you are planning on saving to a file within the same directory as your executable, here's a nice solution that uses the JSON format:
The registry/configurationSettings/XML argument still seems very active. I've used them all, as the technology has progressed, but my favourite is based on Threed's system combined with Isolated Storage.
The following sample allows storage of an objects named properties to a file in isolated storage. Such as:
Properties may be recovered using:
It is just a sample, not suggestive of best practices.