Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to save settings in app.exe.config

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.

like image 234
Mohsan Avatar asked Jul 21 '09 05:07

Mohsan


People also ask

How do I save settings in config file?

Right-click the Designer tab and click Save Config. File. The Saving Configuration to File dialog box appears. Navigate to the location in which you want to save the configuration file.

What is exe config file?

The "appname.exe. config" is automatically created for you when you compile your application. This is the file that should be distributed to your end users (along with the exe file, of course). The settings you set in appname. config is transferred over to appname.exe.


3 Answers

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:

  • OpenExeConfiguration

  • OpenMachineConfiguration

  • OpenMappedExeConfiguration

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> 
like image 117
Chansik Im Avatar answered Oct 05 '22 17:10

Chansik Im


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.

like image 23
awe Avatar answered Oct 05 '22 16:10

awe


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.

  • Unraveling the mysteries of .NET 2.0 configuration
  • Decoding the mysteries of .NET 2.0 configuration
  • Cracking the mysteries of .NET 2.0 configuration

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

like image 45
marc_s Avatar answered Oct 05 '22 16:10

marc_s