3

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?

JKennedy
  • 18,150
  • 17
  • 114
  • 198

2 Answers2

2

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();
         }
    }
}
JKennedy
  • 18,150
  • 17
  • 114
  • 198
0

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;

Community
  • 1
  • 1
pysco68
  • 1,136
  • 9
  • 15