March 3, 2021
Hot Topics:

Building Persistence into .NET Programs

  • By Mike Gunderloy
  • Send Email »
  • More Articles »

If you've read my article Properly Building Persistent Programs, you know the importance of persisting selected information to enhance the user's experience of your applications. But perhaps you're still a bit shakey on the mechanics. In this article, I'll work through a simple persistence example in C#, showing how you can leverage the power of the .NET Framework to store information safely and flexibly.

The Sample Application

Figure 1 shows a simple C# application that can benefit from a bit of persistence. In this case, I want to save the form's size and position, as well as the data entered in the two textboxes. When the form is reloaded in the future, it should use the saved information to initialize itself.

A form in need of persistence

In writing the code, I need to keep several key points in mind:

  1. The application should function normally even if the persisted information can't be found. This will be the case the first time the application is run.
  2. The information should be persisted in a location that is available to all users, even if they are non-administrative or roaming users.
  3. The code should be simple and extensible, so that adding additional persisted information in the future is easy.

It All Starts With a Bit of Class

The first step in my solution is to define a class whose public fields will store the required information:

using System;
namespace Persistence2
	/// <summary>
	/// Class to hold persisted settings
	/// </summary>
	public class Settings
		public int Top;
		public int Left;
		public int Height;
		public int Width;
		public string Name;
		public string Email;

By storing all of the settings in a single class, I can vastly simplify the code to read and writing settings (as you'll see in a bit). The class also makes for easy extensibility; I know that if I need to persist another bit of information, I'll just need to add one more public field to the class. At any time, I'll have at most one instance of this class in my application. In most applications where I use this pattern, I instantiate the class from persisted information when the application is launched, and create a new instance to save when the application is being shut down.

Working Smarter, Not Harder

Now it's time to consider the other requirements. I'll start with saving the settings when the application shuts down. The major problems to be dealt with here are designing a format to hold the settings, and figuring out where to put them. The format must be capable of holding all of the required information. The location must be accessible to all users: administrators, non-administrators, roaming users. Ideally the code should be the same on all supported operating systems.

At this point, the novice programmer might sit down with the MSDN Library and start slinging code, using API calls to retrieve the user's data directory, and writing low-level code to format the persisted information directly to a disk file. But the experienced developer knows that there is a better way to proceed. The .NET Framework includes hundreds of classes and thousands of members. If the application can find the necessary functionality in the Framework, the developer will have to write far less code. As a bonus, functionality that's baked into the Framework has probably had far more testing than your own code will ever see.

Sure enough, there are Framework classes that do just about everything this application needs. In particular, I'll make use of the IsolatedStorageFile class and the SoapFormatter class. Here's my code for saving settings:

using System.IO;
using System.IO.IsolatedStorage;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;

private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		// Get the isolated store for this assembly
	    IsolatedStorageFile isf =

		// Create or truncate the settings file
		// This will ensure that only the object we're
		// saving right now will be in the file
		IsolatedStorageFileStream isfs1 = 
		    new IsolatedStorageFileStream("HTMLBuilderSettings.xml",
		    FileMode.Create, FileAccess.Write, isf);

		// Create a settings object
		Settings s = new Settings();
		s.Top = this.Top;
		s.Left = this.Left;
		s.Height = this.Height;
		s.Width = this.Width;
		s.Name = txtName.Text;
		s.Email = txtEmail.Text;

		// Serialize the object to the file
		SoapFormatter SF = new SoapFormatter();
		SF.Serialize(isfs1, s);

	catch (Exception ex)
	// If settings can't be saved, next 
	// run will just the use form defaults

Page 1 of 2

This article was originally published on June 16, 2003

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date