Using application settings in Windows Phone 7 apps
Join the DZone community and get the full member experience.Join For Free
Many applications have user input that should be somehow preserved in order to be restored when the application starts again. This includes preferences, URLs, general information and whatnot. As in any other .NET application, a Windows Phone 7 application supports application settings.
Although the concept is similar, the way it is implemented is a bit different compared to regular console applications, for example. The way you are used to access them is through Properties.Settings.Default or through the Application Properties dialog. Both of these options are not available in a Windows Phone 7 application.
Instead, you should use IsolatedStorageSettings.ApplicationSettings, which is a member of the System.IO.IsolatedStorage namespace. The application settings are stored in a local application-scoped file that can, in fact, be created via IsolatedStorageFile.GetUserStoreForApplication().CreateFile(path). This, however, would involve direct data manipulation and ApplicationSettings provides the necessary abstraction layer so that you can work with an existing structure without manually working with settings file contents.
ApplicationSettings by itself is an instance of IEnumerable, so you can apply any action to it that applies to enumerable types.
NOTE: Make sure you use unique names for each key. Otherwise, an ArgumentException will be thrown:
This makes it easier to store various class instances and one of the benefits it brings to the table is that you won’t have to serialize the instance manually. The object is restored in the same state it was passed to the Add method.
The advantage of this method is that no KeyNotFoundException will be thrown in case the key is not found. searchedValue will be empty, but at the same time, you won't have to deal with exception handling for this specific method.
Be aware of the fact that in case no key is found, a KeyNotFoundException will be thrown and you need to properly handle it in order to avoid an application crash.
You can also iterate through existing values and keys by using the Values and Keys ICollection-defined properties:
The setting removal is performed pretty much the same way as adding. However, this time you are only referencing the key by which the removed object is identified:
NOTE: No exception will be thrown if the key passed to the Remove method is not found, so you would have to make sure that the entered key is valid.
Opinions expressed by DZone contributors are their own.