Persisting Application Information Across Invocations

How would you persist some sort of C# application settings across multiple invocations of your application?

Bear in mind that this is not a web application specifically — so we can’t throw things into the database. There is no database. Sure, we could add one (SQLite, anyone?) — but what about a more simple approach?

How about just storing information in a (plain-text or XML) file? We could read information on startup, and update the file once, at the end of our application’s life.

This is precisely the built-in mechanism that .NET already provides to you, via the Properties.Settings collection. This class automatically accesses the Settings.Settings file (which exists, by default, in new C# projects) and pulls information into strongly-typed variables.

Let’s say you had an application that asked the user their name, and on subsequent invocations, printed “Hello, !” Here’s how we would go about implementing this using the Properties.Settings class:

  1. Settings.settings File: Verify that your project has a Settings.settings file in the Properties folder. If it doesn’t, right-click your project, add a new item, and pick “Settings File,” and you’re ready to go.
  2. Add the Property: Double-click on the new Settings.settings file. Enter values in the new row: UserName for the property name, string for the type, User for the scope (more on this in a sec), and an empty value.
  3. To print out the stored user’s name, you could write Properties.Settings.Default.UserName — notice that the attribute exists, and that it’s typed as a string, and automatically de-persisted from the settings file (which is just a text file).

    To change the saved user name, it would be the same — with two caveats. First, you need to call Properties.Settings.Default.Save() to save the updated values (it’s not done automatically).

    Second, if you specified the UserName property scope as Application instead of User, it would be read-only. The only chance to change the value would be at design-time, prior to compilation.

    Whether using the Settings.settings file is a good idea is a whole other discussion. At a minimum, I would recommend that you run some sanity checks when you start up your application, to make sure it hasn’t been tampered with. (Better yet, hash the file, store the hash, and use that to make sure it hasn’t been tampered with.)

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.
This entry was posted in Core .NET, Wndows Forms and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *