删除损坏的user.config而不是System.ConfigurationErrorException

问题描述 投票:1回答:1

我正在使用user.config来存储我的应用程序设置。我可以使用Properties.Settings.Default.Setting1访问C#中的设置,user.config文件如下所示:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <userSettings>
        <MyApp.Properties.Settings>
            <setting name="Setting1" serializeAs="String">
                <value>ABCDEF</value>
            </setting>
        </MyApp.Properties.Settings>
    </userSettings>
</configuration>

但是当我的user.config因为什么原因而腐败时,我的应用程序崩溃了下面的System.ConfigurationErrorException

在这种情况下,我更希望应用程序删除损坏的user.config文件并以默认设置启动。

有没有办法实现这一目标?

更新

我看过这个问题之前有人问过user.config corruption issueUser.config corruption

但是,如果我尝试以下代码

// Check for corrupt settings
try
{
    var dummy = Properties.Settings.Default.Setting1;
}
catch (ConfigurationErrorsException exception)
{
    Console.WriteLine("Settings are corrupt!");
    File.Delete(exception.Filename); 
}

exception.Filenamenull。如果我在ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal)块中使用try,则不会在所有情况下都引发异常。

c# app-config
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.