JKennedy
JKennedy

Reputation: 18799

How to restore Configuration Settings when they fail to initialize

I have my program which has some Application Settings and some User Settings. On some machines my User Settings config file becomes corrupt and stops my program loading. I then log into the machine and delete the UserConfig directory stored at %USERPROFILE%\Appdata\Local\MyApp

When my file is corrupt the error thrown is Configuration Settings Failed To Initialize so I was wondering if this happened in my program whether there was a way to delete the corrupt file and reset the configuration.

So far I have:

try
{
     var prop1= Settings.Default.prop1;
}
catch (Exception ex)
{
    var userSettingsLocation =
      Path.Combine(Environment.ExpandEnvironmentVariables(
        "%USERPROFILE%"), "AppData","Local", "MyApp");
    if (Directory.Exists(userSettingsLocation))
    {
      DeleteDirectory(userSettingsLocation); // This is a reccursive
                                             // delete method
      // I need to reload settings
    }
}

This deletes the file fine but if I try to read my settings again using for example: Settings.Reset(); I still get the same error. I need to somehow reset the configuration Settings after deleting the corrupt file. Is this possible?

Upvotes: 3

Views: 1110

Answers (2)

JKennedy
JKennedy

Reputation: 18799

So heres the trick if anyone else wants to know:

try
{
     var prop1= Settings.Default.prop1;
}
catch (Exception ex)
{
    var userSettingsLocation =
      Path.Combine(Environment.ExpandEnvironmentVariables(
        "%USERPROFILE%"), "AppData","Local", "MyApp");
    if (Directory.Exists(userSettingsLocation))
    {
         if (ex.InnerException is System.Configuration.ConfigurationException)
         {
             var settingsFile = (ex.InnerException as ConfigurationException).Filename;
             File.Delete(settingsFile);
             System.Windows.Forms.Application.Restart();
         }
    }
}

Upvotes: 2

pysco68
pysco68

Reputation: 1146

Edit: after some trials, I think you need to restart the application after deleting the faulty config file. Here another SO thread: C# - User Settings broken

The last answer there is essentially the code you could use.


Actually I think you must call Settings.Reset after deleting the file.

By the way you should use the exception details to get the config file name causing the issue:

catch(Exception ex) 
{
    if(ex.InnerException is ConfigurationErrorsException)
    {

        var settingsFile = (e.InnerException as ConfigurationErrorsException).Filename;
        /* ....Your code... */

    }
}

string filename (()e.InnerException).Filename;

Upvotes: 0

Related Questions