WPF/C#: Where should I be saving user preferences files?

You can use the Application Settings easily enough.

If you haven’t done so before just right click on the project and choose Properties. Select the Settings tab. Make sure you chose “User” for the scope (otherwise the setting is read-only).

The code to access this is simple:

forms.Width = Application1.Properties.Settings.Default.Width;

If you need to save it:

Application1.Properties.Settings.Default.Width = forms.Width;
Application1.Properties.Settings.Default.Save();

In the sample above, Width is the custom setting name you define in the Settings tab and Application1 is the Namespace of your application.

Edit: Responding to further questions

You mentioned you wanted to store Dictionary objects in the Settings. As you discovered, you can’t do this directly because Dictionary objects are not serializable. However, you can create your own serializable dictionary pretty easily. Paul Welzer had an excellent example on his blog.

You have a couple of links which sort of muddy the situation a little. Your original question is where to save “User Preference Files”. I’m pretty certain Microsoft’s intention with the Settings functionality is exactly that… storing user skin preferences, layout choices, etc. It not meant as a generic repository for an application’s data although it could be easily abused that way.

The data is stored in separate places for a good reason. Some of the settings are Application settings and are read-only. These are settings which the app needs to function but is not specific to a user (for example, URIs to app resources or maybe a tax rate). These are stored in the app.config.

User settings are stored in an obfuscated directory deep within the User Document/Settings folder. The defaults are stored in app.config (I think, can’t recall for certain off the top of my head) but any user changes are stored in their personal folder. This is meant for data that changes from user to user. (By “user” I mean Windows user, not your app’s user.)

Hope this clarified this somewhat for you. The system is actually pretty simple. It might seem a little foreign at first but after a few days of using it you’ll never have to think of it again… it just works.

Leave a Comment