views:

919

answers:

4

hi..

i am facing one problem.

i want to save settings in app.config file

i wrote separate class and defined section in config file..

but when i run the application. it does not save the given values into config file

here is SettingsClass

public class MySetting:ConfigurationSection
    {
        private static MySetting settings = ConfigurationManager.GetSection("MySetting") as MySetting;

        public override bool IsReadOnly()
        {
            return false;
        }

        public static MySetting Settings
        {
            get
            {
                return settings;
            }
        }


        [ConfigurationProperty("CustomerName")]
        public String CustomerName
        {
            get
            {
                return settings["CustomerName"].ToString();
            }
            set
            {
                settings["CustomerName"] = value;
            }
        }


        [ConfigurationProperty("EmailAddress")]
        public String EmailAddress
        {
            get
            {                
                return settings["EmailAddress"].ToString();
            }
            set
            {
                settings["EmailAddress"] = value;
            }
        }


        public static bool Save()
        {
            try
            {
                System.Configuration.Configuration configFile = Utility.GetConfigFile();
                MySetting mySetting = (MySetting )configFile.Sections["MySetting "];

                if (null != mySetting )
                {
                    mySetting .CustomerName = settings["CustomerName"] as string;
                    mySetting .EmailAddress = settings["EmailAddress"] as string;                    

                    configFile.Save(ConfigurationSaveMode.Full);
                    return true;
                }

                return false;
            }
            catch
            {
                return false;
            }
        }
    }

and this is the code from where i am saving the information in config file

private void SaveCustomerInfoToConfig(String name, String emailAddress)
        {            

            MySetting .Settings.CustomerName = name;
            MySetting .Settings.EmailAddress = emailAddress
            MySetting .Save();
        }

and this is app.config

<configuration>
  <configSections>
    <section name="MySettings" type="TestApp.MySettings, TestApp"/>
  </configSections> 

  <MySettings CustomerName="" EmailAddress="" />  
</configuration>

can u tell me where is the error.. i tried alot and read from internet. but still unable to save information in config file..

i ran the application by double clicking on exe file also.

+1  A: 

In order to actually update the config file, you'll need to call .Save() on the Configuration object - not just your config section object.

You should check out Jon Rista's three-part series on .NET 2.0 configuration up on CodeProject.

Highly recommended, well written and extremely helpful! It shows all the ins and outs of dealing with .NET 2.0 and up configuration, and helped me very much getting a grasp on the subject.

Marc

marc_s
i am calling save method of Configuration Object. still it is not saving.
Mohsan
+3  A: 

According to the MSDN: ConfigurationManager.GetSection Method,

The ConfigurationManager.GetSection method accesses run-time configuration information that it cannot change. To change the configuration, you use the Configuration.GetSection method on the configuration file that you obtain by using one of the following Open methods:

However, if you want to update app.config file, I would read it as an xml document and manipulate it as a normal xml document.

Please see the following example: Note: this sample is just for proof-of-concept. Should not be used in production as it is.

using System;
using System.Linq;
using System.Xml.Linq;

namespace ChangeAppConfig
{
    class Program
    {
        static void Main(string[] args)
        {
            MyConfigSetting.CustomerName = "MyCustomer";
            MyConfigSetting.EmailAddress = "[email protected]";
            MyConfigSetting.TimeStamp = DateTime.Now;
            MyConfigSetting.Save();
        }
    }

    //Note: This is a proof-of-concept sample and 
    //should not be used in production as it is.  
    // For example, this is not thread-safe. 
    public class MyConfigSetting
    {
        private static string _CustomerName;
        public static string CustomerName
        {
            get { return _CustomerName; }
            set
            {
                _CustomerName = value;
            }
        }

        private static string _EmailAddress;
        public static string EmailAddress
        {
            get { return _EmailAddress; }
            set
            {
                _EmailAddress = value;
            }
        }

        private static DateTime _TimeStamp;
        public static DateTime TimeStamp
        {
            get { return _TimeStamp; }
            set
            {
                _TimeStamp = value;
            }
        }

        public static void Save()
        {
            XElement myAppConfigFile = XElement.Load(Utility.GetConfigFileName());
            var mySetting = (from p in myAppConfigFile.Elements("MySettings")
                            select p).FirstOrDefault();
            mySetting.Attribute("CustomerName").Value = CustomerName;
            mySetting.Attribute("EmailAddress").Value = EmailAddress;
            mySetting.Attribute("TimeStamp").Value = TimeStamp.ToString();

            myAppConfigFile.Save(Utility.GetConfigFileName());

        }
    }

    class Utility
    {        
        //Note: This is a proof-of-concept and very naive code. 
        //Shouldn't be used in production as it is. 
        //For example, no null reference checking, no file existence checking and etc. 
        public static string GetConfigFileName()
        {            
            const string STR_Vshostexe = ".vshost.exe";
            string appName = Environment.GetCommandLineArgs()[0];

            //In case this is running under debugger. 
            if (appName.EndsWith(STR_Vshostexe))
            {
                appName = appName.Remove(appName.LastIndexOf(STR_Vshostexe), STR_Vshostexe.Length) + ".exe";
            }

            return appName + ".config";
        }
    }
}

I also added "TimeStamp" attribute to MySettings in app.config to check the result easily.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="MySettings" type="TestApp.MySettings, TestApp"/>
  </configSections>

  <MySettings CustomerName="" EmailAddress="" TimeStamp=""/>
</configuration>
Chansik Im
here is code by which i am getting config filepublic static Configuration GetConfigFile(){ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();configFile.ExeConfigFilename = GetConfigFileName();return ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);}
Mohsan
You are using 'ConfigurationManager.GetSection("MySetting")' to set the static variable, settings, in MySettingClass, which cannot be changed according to the MSDN.
Chansik Im
i tried with this one also. still not savingprivate static MySetting settings = (MySetting )Utility.GetConfigFile().GetSection("MySetting ");
Mohsan
It is much easier to use the built-in settings functionality that is provided and automated by Visual Studio. See [my answer](http://stackoverflow.com/questions/1157378/unable-to-save-settings-in-app-exe-config/1157509#1157509).
awe
+2  A: 

In many cases (in a restricted user scenario) the user do not have write access directly to the application config file. To come around this, you need to use the usersettings.

If you right-click your project and select the tab named "Settings", you can make a list of settings that are stored with the config file. If you select the "Scope" to be "User", the setting are automatically stored in the config file using a type that will automatically store the settings under the users AppData area, where the user allways has write access. The settings are also automatically provided as properties created in the Properties\Settings.Designer.cs code file, and are accessible in your code in Properties.Settings.Default .

Example:

Let's say you add a user setting called CustomerName:

On loading the app, you would want to retreive the value from the stored setting ( either default value as it is in the app config, or if it is stored for this user, the config file for the user):

string value = Properties.Settings.Default.CustomerName;

When you want to change the value, just write to it:

Properties.Settings.Default.CustomerName = "John Doe";

When you want to save all the settings, just call Save:

Properties.Settings.Default.Save();

Note that when you develop, the user file will occationally be reset to the default, but this only happens when building the app. When you just run the app, the settings you store will be read from the user-config file for the app.

If you still want to create your own handling of the settings, you can try this once, and look at what VisualStudio has automatically created for you to get an idea of what you need to get this working.

awe
+1  A: 

Be aware that the appname.vshost.exe.Config is reverted to it's the original state at the end of the debugging session. So you might be saving to the file (you can check by using Notepad during execution), then losing the saved contents when the debugging stops.

Dale B.
It is not lost when debugging stops, it is lost when the application is re-built the next time you run. If you try to just run the exe (from file explorer) directly after stopping debug, you will see that the stored values are still there.
awe