是什么原因导致user.config空?我如何恢复无需重新启动?

问题描述 投票:19回答:4

我注意到在其中我的应用程序的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);
}
c# app-config
4个回答
19
投票

我们在应用程序有这个问题 - 我无法找出原因(我的猜测是,我经常写Properties.Settings,但我不知道)。总之,我的解决方法如下。关键是要删除已损坏的文件,并调用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);
    }
}

4
投票

我有一个类似的情况。对我来说,一旦我删除错误的配置文件,我只是让应用程序继续运行。的设置将在下次访问将使用应用程序的默认值。


4
投票

这可能是有点晚了,但我已经做了这方面的一些更多的研究。在user.config文件似乎遭到损坏,原因不明,未让应用程序启动。你可以把一个小的try / catch逻辑在app.xaml.cs和检查,当它启动,以确保这个问题在源头抓。当应用程序启动并尝试以编程方式加载settings.default和失败,它会去除了为用户提供一个选择要删除的文件。

try {
Settings.Default.Reload();
} 
catch ( ConfigurationErrorsException ex ) 
{ 
  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
}

信用 - http://www.codeproject.com/Articles/30216/Handling-Corrupt-user-config-Settings

希望这可以帮助别人:)


0
投票

下面是我们如何解决这个问题。这个函数必须被调用任何使用Properties.Settings之前......否则你会被stucked(由tofutim和avs099描述)。

private bool CheckSettings()
    {
        var isReset = false;
        string filename = string.Empty;

        try
        {
            var UserConfig = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.PerUserRoamingAndLocal);
            filename = UserConfig.FilePath;
            //"userSettings" should be replaced here with the expected label regarding your configuration file
            var userSettingsGroup = UserConfig.SectionGroups.Get("userSettings");
            if (userSettingsGroup != null && userSettingsGroup.IsDeclared == true)
                filename = null; // No Exception - all is good we should not delete config in Finally block
        }
        catch (System.Configuration.ConfigurationErrorsException ex)
        {
            if (!string.IsNullOrEmpty(ex.Filename))
            {
                filename = ex.Filename;
            }
            else
            {
                var innerEx = ex.InnerException as System.Configuration.ConfigurationErrorsException;
                if (innerEx != null && !string.IsNullOrEmpty(innerEx.Filename))
                {
                    filename = innerEx.Filename;
                }
            }
        }
        catch (System.ArgumentException ex)
        {
            Console.WriteLine("CheckSettings - Argument exception");
        }
        catch (SystemException ex)
        {
            Console.WriteLine("CheckSettings - System exception");

        }
        finally
        { 
            if (!string.IsNullOrEmpty(filename))
            {
                if (System.IO.File.Exists(filename))
                {
                    var fileInfo = new System.IO.FileInfo(filename);
                    var watcher
                         = new System.IO.FileSystemWatcher(fileInfo.Directory.FullName, fileInfo.Name);
                    System.IO.File.Delete(filename);
                    isReset = true;
                    if (System.IO.File.Exists(filename))
                    {
                        watcher.WaitForChanged(System.IO.WatcherChangeTypes.Deleted);
                    }

                    try
                    {
                        Properties.Settings.Default.Upgrade();                          
                    } catch(SystemException ex)
                    {
                        Console.WriteLine("CheckSettings - Exception" + ex.Message);
                    }
                }
            } 
        }
        return isReset;
    }
© www.soinside.com 2019 - 2024. All rights reserved.