Click here to Skip to main content
15,881,803 members
Articles / Desktop Programming / Windows Forms
Article

Handling Corrupt "user.config" Settings

Rate me:
Please Sign up or sign in to vote.
4.78/5 (45 votes)
17 Oct 2008CPOL3 min read 154.5K   39   44
Build a simple handler for handling corrupt user settings into your program.

Image 1

Introduction

The Settings class has been with us since .NET 2.0, and is still the simplest and preferred way of storing user settings for your application. However, there is a lingering issue with the Settings mechanism that has yet to be satisfactorily resolved by Microsoft.

Furthermore, it took me quite a while before I actually discovered a solution. Luckily, the result ended up being quite a bit easier than some of my attempts, and although I couldn't find it mentioned anywhere in my searches, I stumbled upon it while debugging one day.

In fact, it turned out to be so simple in retrospect that many of you may have already solved this and thought nothing more of it, but since it took me a while before I realized the solution (and indeed that there was a problem to begin with), I thought others might benefit from having it explicitly laid out.

So, without further ado, here's the problem and solution.

The Problem

The problem is this: if the user.config file gets corrupted (which has happened to me on more than one occasion, entirely on its own), there is seemingly no way to recover from this programmatically, and your program will crash the moment Settings is accessed, every time it is run. What's worse, we can't even call Settings.Default.Reset(), because that method just throws the same exception. Up until now, the only option I had was to instruct users to manually delete their user.config file by rooting through the various hidden settings folders in their user account. This is not something the novice user will appreciate having to do.

What makes this so difficult is the fact that the actual location of the user.config file is so convoluted as to be impossible to determine by hand. For example, here is the path to my OrangeNote user settings file:

C:\Users\Logan\AppData\Local\The_Little_Software_Compa\
  OrangeNote.exe_Url_wxcnyrmstqy3oj1qwckdjq3gjqkq4fel\1.0.0.0\user.config

I don't know about you, but that hash code in there scares the pants off of me, and I don't like the idea of having to figure that out myself. The path will also change depending on whether the assembly is signed with a strong name or not, and other factors like the current version, executable name, company name, etc. Since hard-coding any kind of algorithm would be a pain and would introduce a great many dependencies and therefore potential failure points, I don't consider that an option.

The Solution

Obviously, the solution is to either repair or simply delete the user.config file, but we have to find it before we can do that. I won't get into repairing, since there's no simple way that I know of to do this. In most cases, deleting the user's application settings, while inconvenient, is not the end of the world, so long as the user is given fair warning that this is about to happen. You're free to take other measures, of course.

It turns out, the path to the user.config file was in the exception all along! But, it's sneakily hidden inside an InnerException, and maybe this is why it eluded me at first. So, allow me to present a block of code that will basically handle this occurrence in a universal manner. You should place this block somewhere near the beginning of your application startup, before any call to Settings is made:

C#
try {
    Settings.Default.Reload();
} catch ( ConfigurationErrorsException ex ) { //(requires System.Configuration)
    string filename = ( (ConfigurationErrorsException)ex.InnerException ).Filename;

    if ( MessageBox.Show( "<ProgramName> has detected that your" + 
                          " user settings file has become corrupted. " +
                          "This may be due to a crash or improper exiting" + 
                          " of the program. <ProgramName> must reset your " +
                          "user settings in order to continue.\n\nClick" + 
                          " Yes to reset your user settings and continue.\n\n" +
                          "Click No if you wish to attempt manual repair" + 
                          " or to rescue information before proceeding.",
                          "Corrupt user settings", 
                          MessageBoxButton.YesNo, 
                          MessageBoxImage.Error ) == MessageBoxResult.Yes ) {
        File.Delete( filename );
        Settings.Default.Reload();
        // you could optionally restart the app instead
    } else
        Process.GetCurrentProcess().Kill();
        // avoid the inevitable crash
}

You will need to add a reference to System.Configuration in order to use the ConfigurationErrorsException type. The above code uses the WPF version of MessageBox; you will have to tweak it if you are using Windows Forms.

Trying it Out

To try it out, all you need to do is open your valid user.config file in a text editor and make some change that the parsing engine won't like, such as adding some data to the root, or deleting a closing tag. Then, just launch your application, and you should now receive the appropriate warning.

Points of Interest

If anyone has any alternative solutions, don't hesitate to share them!

History

  • Oct. 17, 2008 - First published.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
President The Little Software Company
Canada Canada
My name is Logan Murray and I'm a Canadian. I'm interested primarily in C# and Windows desktop application development (learning WPF at the moment and then hopefully LINQ), though I hope to branch-out more to the web side of things eventually. I am the president and owner of The Little Software Company and am currently working on the Windows version of OrangeNote, to be released soon. Check out my RSS reader, FeedBeast™.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Anes0816-Sep-23 23:46
Anes0816-Sep-23 23:46 
QuestionThank You Pin
Member 1392213222-Jul-18 20:21
Member 1392213222-Jul-18 20:21 
AnswerRe: Thank You Pin
abdellatif EL GHARABAOUI18-Nov-21 2:10
abdellatif EL GHARABAOUI18-Nov-21 2:10 
PraiseThanks a lot ;) Pin
Member 1268800111-May-17 3:59
Member 1268800111-May-17 3:59 
SuggestionCopy and Retrieve .config file Pin
Gosforth Park21-Sep-16 1:34
Gosforth Park21-Sep-16 1:34 
QuestionSettings.Default.Reload() Pin
Benjamin Holland20-Oct-15 14:11
Benjamin Holland20-Oct-15 14:11 
GeneralExcellent! Pin
isaper16-Sep-15 3:50
isaper16-Sep-15 3:50 
GeneralMy vote of 5 Pin
ssdi14-Feb-14 2:18
ssdi14-Feb-14 2:18 
GeneralMy vote of 5 Pin
Matt Willing29-Aug-13 23:48
Matt Willing29-Aug-13 23:48 
GeneralMy vote of 5 Pin
Mehdi Abbasian6-Jul-13 20:15
Mehdi Abbasian6-Jul-13 20:15 
GeneralMy vote of 5 Pin
Kim Togo18-Jun-12 23:24
professionalKim Togo18-Jun-12 23:24 
QuestionThanks Pin
Cris McRae9-May-12 12:50
Cris McRae9-May-12 12:50 
GeneralMy vote of 5 Pin
Hkpavel4-Jul-11 3:51
Hkpavel4-Jul-11 3:51 
GeneralInner exception did not have the file name Pin
cew1109091-Apr-11 7:39
cew1109091-Apr-11 7:39 
GeneralMy vote of 5 Pin
T_C5-Oct-10 8:04
T_C5-Oct-10 8:04 
GeneralYou don't have to restart the application. Pin
Jarle Sulesund23-Sep-10 23:26
Jarle Sulesund23-Sep-10 23:26 
PraiseRe: You don't have to restart the application. Pin
Member 1268800111-May-17 4:01
Member 1268800111-May-17 4:01 
Answera possible solution Pin
malac15-May-10 1:13
malac15-May-10 1:13 
Generalthanks, too Pin
rj2Skipper25-Nov-09 1:59
rj2Skipper25-Nov-09 1:59 
Generalsolution variant Pin
dimanamid24-Sep-09 22:51
dimanamid24-Sep-09 22:51 
JokeThanks!! Pin
dimanamid24-Sep-09 22:08
dimanamid24-Sep-09 22:08 
GeneralSmall Improvment Pin
doronkuk1-Aug-09 23:59
doronkuk1-Aug-09 23:59 
GeneralMy vote of 2 Pin
Priyank Bolia9-Apr-09 5:54
Priyank Bolia9-Apr-09 5:54 
GeneralSettings.Default.Reload() does not throw exception with currupted user.config Pin
MDummy16-Mar-09 0:46
MDummy16-Mar-09 0:46 
GeneralRe: Settings.Default.Reload() does not throw exception with currupted user.config Pin
Cris McRae9-May-12 12:53
Cris McRae9-May-12 12:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.