简体   繁体   English

无法在app.exe.config中保存设置

[英]unable to save settings in app.exe.config

i am facing one problem. 我正面临一个问题。

i want to save settings in app.config file 我想在app.config文件中保存设置

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 这是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 这是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. 我也通过双击exe文件来运行应用程序。

According to the MSDN: ConfigurationManager.GetSection Method , 根据MSDN:ConfigurationManager.GetSection方法

The ConfigurationManager.GetSection method accesses run-time configuration information that it cannot change . ConfigurationManager.GetSection方法访问无法更改的运行时配置信息。 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: 要更改配置,请在使用以下Open方法之一获取的配置文件上使用Configuration.GetSection方法:

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. 但是,如果要更新app.config文件,我会将其作为xml文档读取并将其作为普通的xml文档进行操作。

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 = "MyCustomer@Company.com";
            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. 我还在app.config中为MySettings添加了“TimeStamp”属性,以便轻松检查结果。

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

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

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. 要解决这个问题,您需要使用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. 如果选择“范围”为“用户”,则设置将自动存储在配置文件中,该类型将自动将设置存储在用户AppData区域下,用户始终具有写访问权限。 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 . 这些设置也会自动作为在Properties \\ Settings.Designer.cs代码文件中创建的属性提供,并且可以在Properties.Settings.Default中的代码中访问。

Example: 例:

Let's say you add a user setting called CustomerName : 假设您添加了一个名为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. 如果您仍想创建自己的设置处理,可以尝试一次,然后查看VisualStudio为您自动创建的内容,以了解实现此功能所需的内容。

In order to actually update the config file, you'll need to call .Save() on the Configuration object - not just your config section object. 为了实际更新配置文件,您需要在Configuration对象上调用.Save() - 而不仅仅是您的配置节对象。

You should check out Jon Rista's three-part series on .NET 2.0 configuration up on CodeProject. 您应该在CodeProject上查看Jon Rista关于.NET 2.0配置的三部分系列。

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. 它显示了处理.NET 2.0和up配置的所有细节,并帮助我非常了解这个主题。

Marc

Be aware that the appname.vshost.exe.Config is reverted to it's the original state at the end of the debugging session. 请注意,appname.vshost.exe.Config将恢复为调试会话结束时的原始状态。 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. 因此您可能正在保存到该文件(您可以在执行期间使用记事本进行检查),然后在调试停止时丢失已保存的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM