正在从 XML 加载用户设置,但 settings.Object 未设置为对象实例

Loading user settings from XML with settings.Object not set to an instance of object

我的 WinForm 程序保存了一份 xml 用户设置副本,我遇到的问题是重新加载它。

我从博客中复制了这段代码:Code Snippet

错误发生在下面代码注释的地方。

Could not import settings. Object reference not set to an instance of an object.

[更新] 我刚刚注意到它在 运行 从 Visual Studio 2013 开始运行程序时确实有效,但是当 运行 来自 Windows 文件资源管理器。

[Update2] 我想因为这是我第一次从桌面上 运行 这个,我是一个不同的用户和我的用户设置配置文件还没有创建,就是这个问题

try{
    var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);

    // returns "[MyApplication].Properties.Settings";
    string appSettingsXmlName = Properties.Settings.Default.Context["GroupName"].ToString();
    // Open settings file as XML
    var import = XDocument.Load(filename);
    // Get the whole XML inside the settings node
    var settings = import.XPathSelectElements("//" + appSettingsXmlName);

    //***Error occurs in the following code***
    config.GetSectionGroup("userSettings")
        .Sections[appSettingsXmlName]
        .SectionInformation
        .SetRawXml(settings.Single().ToString());

    config.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection("userSettings");

    appSettings.Reload();
}
catch (Exception ex)
{
    MessageBox.Show("Could not import settings. " + ex.Message);
}

这是 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="DropLib.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
        </sectionGroup>
    </configSections>
    <userSettings>
        <DropLib.Properties.Settings>
            <setting name="ORG_SETTINGS" serializeAs="Xml">
                <value>
                    <ArrayOfString xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                        <string>ORG1-||-server1-||-Proj 94-||-email@ORG1.com-|||-Server-|-Server-|-Folder$-|-http://server1/proj-|-c:\inetpub\wwwroot\proj\</string>
                        <string>ORG2-||-server2-||-Proj 94-||-email@ORG2.com-|||-Server-|-Server-|-Folder$-|-http://server2/proj-|-c:\inetpub\wwwroot\proj\</string>
                    </ArrayOfString>
                </value>
            </setting>
        </DropLib.Properties.Settings>
    </userSettings>
</configuration>

看来您是不同的用户,具体取决于您是 运行 来自 VS 还是来自桌面。

当我第一次从桌面运行程序时,还没有创建user.config文件。

解决方案:添加检查以查看 user.config 是否已创建,如果没有执行用户设置的保存,这将创建它。

新代码:

try
{
    var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
    //Check user.config exists
    if (!File.Exists(config.FilePath))
    {
        [EDIT]
        DropLib.Properties.Settings.Default.MY_SETTING = "";
        [/EDIT]
        DropLib.Properties.Settings.Default.Save();
        config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
    }

    // returns "[MyApplication].Properties.Settings";
    string appSettingsXmlName = Properties.Settings.Default.Context["GroupName"].ToString();

    // Open settings file as XML
    var import = XDocument.Load(filename);

    // Get the whole XML inside the settings node
    var settings = import.XPathSelectElements("//" + appSettingsXmlName);

    config.GetSectionGroup("userSettings")
        .Sections[appSettingsXmlName]
        .SectionInformation
        .SetRawXml(settings.Single().ToString());

    config.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection("userSettings");

    appSettings.Reload();
}
catch (Exception ex)
{
    MessageBox.Show("Could not import settings. " + ex.Message);
    appSettings.Reload(); // from last set saved, not defaults
}