是什么导致user.config为空?如何在不重新启动的情况下恢复?

Jer*_*myK 19 c# app-config

我注意到在我的应用程序的user.config文件以某种方式损坏并在打开时为空的几台机器上.我似乎无法弄清楚为什么会这样.是否有一个常见的事情会导致这种情况?有什么方法可以安全地防止这个

我的第二个问题是如何恢复状态?我捕获异常并删除user.config文件,但我找不到一种方法来恢复配置而不重新启动应用程序.我在Properties对象上执行的所有操作都会导致以下错误:

"配置系统无法初始化"

重置,重新加载和升级都无法解决问题.

这是我在异常后删除的代码:

catch (System.Configuration.ConfigurationErrorsException ex)
{
    string fileName = "";
    if (!string.IsNullOrEmpty(ex.Filename))
        fileName = ex.Filename;
    else
    {
        System.Configuration.ConfigurationErrorsException innerException = ex.InnerException as System.Configuration.ConfigurationErrorsException;
        if (innerException != null && !string.IsNullOrEmpty(innerException.Filename))
            fileName = innerException.Filename;
    }
    if (System.IO.File.Exists(fileName))
        System.IO.File.Delete(fileName);
}
Run Code Online (Sandbox Code Playgroud)

avs*_*099 19

我们在我们的应用程序中遇到了这个问题 - 而且我无法找到原因(我的猜测是我写的很常见,但我不太确定).无论如何,我的解决方法是在下面.关键是删除损坏的文件并调用Properties.Settings.Default.Upgrade()

try
{
     ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
}
catch (ConfigurationErrorsException ex)
{
    string filename = ex.Filename;
    _logger.Error(ex, "Cannot open config file");

    if (File.Exists(filename) == true)
    {
        _logger.Error("Config file {0} content:\n{1}", filename, File.ReadAllText(filename));
        File.Delete(filename);
        _logger.Error("Config file deleted");
        Properties.Settings.Default.Upgrade();
        // Properties.Settings.Default.Reload();
        // you could optionally restart the app instead
    }
    else
    {
        _logger.Error("Config file {0} does not exist", filename);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 实际上,这确实有效 - 但是重要的是使用openexeconfiguration而不是调用错误的设置,在调用错误的设置后,你会遇到配置系统无法初始化 (3认同)
  • 这是一个胜利者-关键是openexeconfiguration-如果不触发“配置系统初始化失败”错误,您甚至可以交换user.config的备份版本 (2认同)