使用settings从对象加载用户设置。对象未设置为对象

时间:2016-05-17 01:45:11

标签: c# xml winforms configurationmanager

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

我已从博客中复制此代码:Code Snippet

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

  

无法导入设置。对象引用未设置为实例   一个对象。

[更新] 我刚刚注意到它在从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>

1 个答案:

答案 0 :(得分:1)

根据您从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
}