Posted By

pckujawa on 12/08/09


Tagged

file WinForms saving restoring persistence


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

vali29
Priestd09
danfinrud55


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


 / Published in: C#
 

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

References: msdn blog, devX

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://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

  1. Exported file:
  2. <?xml version="1.0" encoding="utf-8"?>
  3. <configuration>
  4. <userSettings>
  5. <HawkConfigGUI.Properties.Settings>
  6. <setting name="FpgaFilePath" serializeAs="String">
  7. <value>testfpga</value>
  8. </setting>
  9. <setting name="FirmwareFilePath" serializeAs="String">
  10. <value>test</value>
  11. </setting>
  12. </HawkConfigGUI.Properties.Settings>
  13. </userSettings>
  14. </configuration>
  15.  
  16. Class:
  17. using System;
  18. using System.Configuration;
  19. using System.IO;
  20. using System.Linq;
  21. using System.Xml.Linq;
  22. using System.Xml.XPath;
  23.  
  24. public static class SettingsIO
  25. {
  26. internal static void Import(string settingsFilePath)
  27. {
  28. if (!File.Exists(settingsFilePath))
  29. {
  30. throw new FileNotFoundException();
  31. }
  32.  
  33. var appSettings = Properties.Settings.Default;
  34. try
  35. {
  36. var config =
  37. ConfigurationManager.OpenExeConfiguration(
  38. ConfigurationUserLevel.PerUserRoamingAndLocal);
  39.  
  40. string appSettingsXmlName =
  41. Properties.Settings.Default.Context["GroupName"].ToString();
  42. // returns "MyApplication.Properties.Settings";
  43.  
  44. // Open settings file as XML
  45. var import = XDocument.Load(settingsFilePath);
  46. // Get the whole XML inside the settings node
  47. var settings = import.XPathSelectElements("//" + appSettingsXmlName);
  48.  
  49. config.GetSectionGroup("userSettings")
  50. .Sections[appSettingsXmlName]
  51. .SectionInformation
  52. .SetRawXml(settings.Single().ToString());
  53. config.Save(ConfigurationSaveMode.Modified);
  54. ConfigurationManager.RefreshSection("userSettings");
  55.  
  56. appSettings.Reload();
  57. }
  58. catch (Exception) // Should make this more specific
  59. {
  60. // Could not import settings.
  61. appSettings.Reload(); // from last set saved, not defaults
  62. }
  63. }
  64.  
  65. internal static void Export(string settingsFilePath)
  66. {
  67. Properties.Settings.Default.Save();
  68. var config =
  69. ConfigurationManager.OpenExeConfiguration(
  70. ConfigurationUserLevel.PerUserRoamingAndLocal);
  71. config.SaveAs(settingsFilePath);
  72. }
  73. }

Report this snippet  

You need to login to post a comment.