Return to Snippet

Revision: 21287
at March 12, 2010 17:16 by pckujawa


Updated Code
Exported file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <userSettings>
        <HawkConfigGUI.Properties.Settings>
            <setting name="FpgaFilePath" serializeAs="String">
                <value>testfpga</value>
            </setting>
            <setting name="FirmwareFilePath" serializeAs="String">
                <value>test</value>
            </setting>
        </HawkConfigGUI.Properties.Settings>
    </userSettings>
</configuration>

Class:
using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;

public static class SettingsIO
{
    internal static void Import(string settingsFilePath)
    {
        if (!File.Exists(settingsFilePath))
        {
            throw new FileNotFoundException();
        }

        var appSettings = Properties.Settings.Default;
        try
        {
            var config = 
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.PerUserRoamingAndLocal);

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

            // Open settings file as XML
            var import = XDocument.Load(settingsFilePath);
            // 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) // Should make this more specific
        {
            // Could not import settings.
            appSettings.Reload(); // from last set saved, not defaults
        }
    }

    internal static void Export(string settingsFilePath)
    {
        Properties.Settings.Default.Save();
        var config = 
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.PerUserRoamingAndLocal);
        config.SaveAs(settingsFilePath);
    }
}

Revision: 21286
at December 9, 2009 17:31 by pckujawa


Updated Code
Exported file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <userSettings>
        <HawkConfigGUI.Properties.Settings>
            <setting name="FpgaFilePath" serializeAs="String">
                <value>testfpga</value>
            </setting>
            <setting name="FirmwareFilePath" serializeAs="String">
                <value>test</value>
            </setting>
        </HawkConfigGUI.Properties.Settings>
    </userSettings>
</configuration>

Class:
using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
using AedUtils;

namespace HawkConfigGUI
{
    public static class SettingsIO
    {
        private static NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();

        internal static void Import(string settingsFilePath)
        {
            if (!File.Exists(settingsFilePath))
            {
                throw new FileNotFoundException();
            }

            var appSettings = Properties.Settings.Default;
            try
            {
                // Open settings file as XML
                var import = XDocument.Load(settingsFilePath);
                // Get the <setting> elements
                var settings = import.XPathSelectElements("//setting");
                foreach (var setting in settings)
                {
                    string name = setting.Attribute("name").Value;
                    string value = setting.XPathSelectElement("value").FirstNode.ToString();

                    try
                    {
                        appSettings[name] = value; // throws SettingsPropertyNotFoundException
                    }
                    catch (SettingsPropertyNotFoundException spnfe)
                    {
                        _logger.WarnException("An imported setting ({0}) did not match an existing setting.".FormatString(name), spnfe);
                    }
                }
            }
            catch (Exception exc)
            {
                _logger.ErrorException("Could not import settings.", exc);
                appSettings.Reload(); // from last set saved, not defaults
            }
        }

        internal static void Export(string settingsFilePath)
        {
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
            config.SaveAs(settingsFilePath);
        }
    }
}

Revision: 21285
at December 9, 2009 17:22 by pckujawa


Updated Code
using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
using AedUtils;

namespace HawkConfigGUI
{
    public static class SettingsIO
    {
        private static NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();

        internal static void Import(string settingsFilePath)
        {
            if (!File.Exists(settingsFilePath))
            {
                throw new FileNotFoundException();
            }

            var appSettings = Properties.Settings.Default;
            try
            {
                // Open settings file as XML
                var import = XDocument.Load(settingsFilePath);
                // Get the <setting> elements
                var settings = import.XPathSelectElements("//setting");
                foreach (var setting in settings)
                {
                    string name = setting.Attribute("name").Value;
                    string value = setting.XPathSelectElement("value").FirstNode.ToString();

                    try
                    {
                        appSettings[name] = value; // throws SettingsPropertyNotFoundException
                    }
                    catch (SettingsPropertyNotFoundException spnfe)
                    {
                        _logger.WarnException("An imported setting ({0}) did not match an existing setting.".FormatString(name), spnfe);
                    }
                }
            }
            catch (Exception exc)
            {
                _logger.ErrorException("Could not import settings.", exc);
                appSettings.Reload(); // from last set saved, not defaults
            }
        }

        internal static void Export(string settingsFilePath)
        {
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
            config.SaveAs(settingsFilePath);
        }
    }
}

Revision: 21284
at December 9, 2009 12:42 by pckujawa


Updated Code
internal static void Export(string settingsFilePath)
{
    var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
    config.SaveAs(settingsFilePath);
}

Revision: 21283
at December 8, 2009 18:24 by pckujawa


Initial Code
in progress

Initial URL
http://articles.techrepublic.com.com/5100-10878_11-1044975.html

Initial Description
References: [msdn blog](http://blogs.msdn.com/youssefm/archive/2010/01/21/how-to-change-net-configuration-files-at-runtime-including-for-wcf.aspx), [devX](http://www.devx.com/dotnet/Article/41639/0/page/1)

The .NET framework provides XML configuration files (in the Properties->Settings area of a C# project or in app.config) which make it easy to bind and save/restore data between application executions. I want to take it one step further and allow the user to save and restore multiple versions of these config files, rather than just relying on the last-entered data.

To get a file with any saved user settings, do this:  

    internal static void Export(string settingsFilePath)
    {
        Properties.Settings.Default.Save();
        var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
        config.SaveAs(settingsFilePath);
    }

The ConfigurationUserLevel setting is important; it determines whether you get the file you see in Settings.settings or the file which has the user's custom data.

(See example output file in source, as it won't show up correctly here.)

To import the settings in a file, you can use the Import method below. [EDIT: This is the old method which only works for settings persisted as strings. The Import code in the Source window is much better and more robust. I'm just leaving this in for reference.]

    internal static void Import(string settingsFilePath)
    {
        if (!File.Exists(settingsFilePath))
        {
            throw new FileNotFoundException();
        }

        var appSettings = Properties.Settings.Default;
        try
        {
            // Open settings file as XML
            var import = XDocument.Load(settingsFilePath);
            // Get the <setting> elements
            var settings = import.XPathSelectElements("//setting");
            foreach (var setting in settings)
            {
                string name = setting.Attribute("name").Value;
                string value = setting.XPathSelectElement("value").FirstNode.ToString();

                try
                {
                    appSettings[name] = value; // throws SettingsPropertyNotFoundException
                }
                catch (SettingsPropertyNotFoundException spnfe)
                {
                    _logger.WarnException("An imported setting ({0}) did not match an existing setting.".FormatString(name), spnfe);
                }
            }
        }
        catch (Exception exc)
        {
            _logger.ErrorException("Could not import settings.", exc);
            appSettings.Reload(); // from last set saved, not defaults
        }
    }

References:  
[My question on StackOverflow](http://stackoverflow.com/questions/1869628/how-to-use-net-configuration-files-app-config-settings-settings-to-save-and-r)   

http://articles.techrepublic.com.com/5100-10878_11-1044975.html  

http://chiragrdarji.wordpress.com/2008/09/25/how-to-change-appconfig-file-run-time-using-c/  

http://msdn.microsoft.com/en-us/library/system.configuration.configuration.aspx  

http://stackoverflow.com/questions/132544/net-configuration-app-config-web-config-settings-settings  

[Saving Settings in .NET 2.0 Apps](http://www.ddj.com/windows/187002743)

Initial Title
Persisting data using XML config files in WinForms (saving and restoring user and application data)

Initial Tags
file

Initial Language
C#