Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 如何编辑应用程序配置设置?App.config最好的方法是什么?_.net_Configuration_Settings_App Config - Fatal编程技术网

.net 如何编辑应用程序配置设置?App.config最好的方法是什么?

.net 如何编辑应用程序配置设置?App.config最好的方法是什么?,.net,configuration,settings,app-config,.net,Configuration,Settings,App Config,对于我的项目,我有通过项目属性中的设置添加的设置 我很快发现,直接编辑app.config文件似乎并没有真正更新设置值。似乎我必须在进行更改并重新编译时查看项目属性 我想知道。。。什么是最好的 也是处理可自定义设置的最简单方法 对于一个项目,我想这会 如何使用.Net成为一个无脑的人 处理它。。。我真丢脸 是否可以使用其中一种方法 设置,AppSettings, 应用程序设置,或用户设置来处理此问题 将我的设置写入自定义配置文件并自己处理是否更好 现在我正在寻找最快的解决方案 我的环境是C#

对于我的项目,我有通过项目属性中的设置添加的设置

我很快发现,直接编辑app.config文件似乎并没有真正更新设置值。似乎我必须在进行更改并重新编译时查看项目属性

  • 我想知道。。。什么是最好的 也是处理可自定义设置的最简单方法 对于一个项目,我想这会 如何使用.Net成为一个无脑的人 处理它。。。我真丢脸

  • 是否可以使用其中一种方法 设置,AppSettings应用程序设置,或用户设置来处理此问题

将我的设置写入自定义配置文件并自己处理是否更好

现在我正在寻找最快的解决方案

我的环境是C#、.Net 3.5和Visual Studio 2008。

更新

我正在努力做到以下几点:

    protected override void Save()
    {
        Properties.Settings.Default.EmailDisplayName = this.ddEmailDisplayName.Text;
        Properties.Settings.Default.Save();
    }

编译时出现只读错误。

编辑:我的错误。我误解了原来问题的目的

原文:

我们通常直接在app.config文件中设置设置,但通常这是用于自定义设置

示例app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="MySection" type="System.Configuration.NameValueFileSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    </configSections>
    <connectionStrings>
        <add name="Default" connectionString="server=MyServer;database=MyDatabase;uid=MyDBUser;password=MyDBPassword;connection timeout=20" providerName="System.Data.SqlClient" />
    </connectionStrings>
    <MySection>
        <add key="RootPath" value="C:\MyDirectory\MyRootFolder" /> <!-- Path to the root folder. -->
        <add key="SubDirectory" value="MySubDirectory" /> <!-- Name of the sub-directory. -->
        <add key="DoStuff" value="false" /> <!-- Specify if we should do stuff -->
    </MySection>
</configuration>
//This method will read the value of the OptionsPortNumber in the
//above app.config file.
private void UpdateConfigData()
    {
        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
        doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);


        //Looping through all nodes.
        foreach (XmlNode node in doc.ChildNodes.Item(1))
        {
        //Searching for the node “”
            if (node.LocalName == "appSettings")
            {
                if (!dynamicRefreshCheckBox.Checked)
                {
                    node.ChildNodes.Item(1).Attributes[1].Value = this.portNumberTextBox.Text;
                }
                else
                {
                    node.ChildNodes.Item(1).Attributes[1].Value = Convert.ToString(0);
                }
            }
        }
        //Saving the Updated values in App.config File.Here updating the config
        //file in the same path.
        doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
    }

不确定这是否是您想要的,但您可以从应用程序中更新并保存设置:

ConsoleApplication1.Properties.Settings.Default.StringSetting=“测试”;
ConsoleApplication1.Properties.Settings.Default.Save()

您如何在代码中引用设置类?您是使用默认实例还是创建新的设置对象?我相信默认实例使用设计器生成的值,只有在打开属性时才会从配置文件中重新读取该值。如果创建一个新对象,我认为该值直接从配置文件本身读取,而不是从设计器生成的属性读取,除非app.config文件中不存在该设置

通常,我的设置将在库中,而不是直接在应用程序中。我在属性文件中设置了有效的默认值。然后,我可以通过在应用程序的配置(web.config或app.config,视情况而定)中添加适当的配置部分(从库app.config文件中检索和修改)来覆盖这些内容

使用:

 Settings configuration = new Settings();
 string mySetting = configuration.MySetting;
而不是:

 string mySetting = Settings.Default.MySetting;

是我的钥匙。

你的答案可能在这里:
这太傻了。。。我想我必须为浪费大家的时间而道歉!但是看起来我只需要将作用域设置为User而不是Application,然后我就可以写入新值了

 System.Configuration.Configuration config =ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        config.AppSettings.Settings["oldPlace"].Value = "3";     
        config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("appSettings");
试试这段代码,很简单

Atte:Erick Siliezar

试试这个:

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <configSections>
   <!--- ->
  </configSections>

  <userSettings>
   <Properties.Settings>
      <setting name="MainFormSize" serializeAs="String">
        <value>
1022, 732</value>
      </setting>
   <Properties.Settings>
  </userSettings>

  <appSettings>
    <add key="TrilWareMode" value="-1" />
    <add key="OptionsPortNumber" value="1107" />
  </appSettings>

</configuration>
正在更新App.config中的值:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="MySection" type="System.Configuration.NameValueFileSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    </configSections>
    <connectionStrings>
        <add name="Default" connectionString="server=MyServer;database=MyDatabase;uid=MyDBUser;password=MyDBPassword;connection timeout=20" providerName="System.Data.SqlClient" />
    </connectionStrings>
    <MySection>
        <add key="RootPath" value="C:\MyDirectory\MyRootFolder" /> <!-- Path to the root folder. -->
        <add key="SubDirectory" value="MySubDirectory" /> <!-- Name of the sub-directory. -->
        <add key="DoStuff" value="false" /> <!-- Specify if we should do stuff -->
    </MySection>
</configuration>
//This method will read the value of the OptionsPortNumber in the
//above app.config file.
private void UpdateConfigData()
    {
        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
        doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);


        //Looping through all nodes.
        foreach (XmlNode node in doc.ChildNodes.Item(1))
        {
        //Searching for the node “”
            if (node.LocalName == "appSettings")
            {
                if (!dynamicRefreshCheckBox.Checked)
                {
                    node.ChildNodes.Item(1).Attributes[1].Value = this.portNumberTextBox.Text;
                }
                else
                {
                    node.ChildNodes.Item(1).Attributes[1].Value = Convert.ToString(0);
                }
            }
        }
        //Saving the Updated values in App.config File.Here updating the config
        //file in the same path.
        doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
    }

我也遇到了同样的问题,直到我意识到我是在调试模式下运行应用程序,因此我的新应用程序设置的密钥正在写入[applicationName]。vshost.exe.config文件

一旦应用程序关闭,这个vshost.exe.config文件就不会保留任何新密钥——它会恢复为[applicationName]。exe.config文件的内容


我在调试器之外测试了它,这里和其他地方添加配置appSetting键的各种方法都可以正常工作。新密钥已添加到:[applicationName]。exe.config

我也尝试解决此问题,现在我有了一个漂亮的控制台应用程序,我想与大家分享:(App.config)

您将看到:

  • 如何读取所有AppSetting属性
  • 如何插入新属性
  • 如何删除属性
  • 如何更新属性
  • 玩得开心

        public void UpdateProperty(string key, string value)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            KeyValueConfigurationCollection appSettings = config.AppSettings.Settings;
    
    
            // update SaveBeforeExit
            config.AppSettings.Settings[key].Value = value;
            Console.Write("...Configuration updated: key "+key+", value: "+value+"...");
    
            //save the file
            config.Save(ConfigurationSaveMode.Modified);
            Console.Write("...saved Configuration...");
            //relaod the section you modified
            ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);
            Console.Write("...Configuration Section refreshed...");
        }
    
        public void ReadAppSettingsProperty()
        {
            try
            {
                var section = ConfigurationManager.GetSection("applicationSettings");
    
                // Get the AppSettings section.
                NameValueCollection appSettings = ConfigurationManager.AppSettings;
    
                // Get the AppSettings section elements.
                Console.WriteLine();
                Console.WriteLine("Using AppSettings property.");
                Console.WriteLine("Application settings:");
    
                if (appSettings.Count == 0)
                {
                Console.WriteLine("[ReadAppSettings: {0}]", "AppSettings is empty Use GetSection command first.");
                }
                for (int i = 0; i < appSettings.Count; i++)
                {
                    Console.WriteLine("#{0} Key: {1} Value: {2}",
                    i, appSettings.GetKey(i), appSettings[i]);
                }
            }
            catch (ConfigurationErrorsException e)
            {
                Console.WriteLine("[ReadAppSettings: {0}]", e.ToString());
            }
    
        }
    
    
        public void updateAppSettingProperty(string key, string value)
        {
            // Get the application configuration file.
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            string sectionName = "appSettings";
    
    
            config.AppSettings.Settings.Remove(key);
            config.AppSettings.Settings.Add(key, value);
    
            SaveConfigFile(config);
        }
    
        public void insertAppSettingProperty(string key, string value)
        {
            // Get the application configuration file.
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            string sectionName = "appSettings";
    
            config.AppSettings.Settings.Add(key, value);
    
            SaveConfigFile(config);
        }
    
        public void deleteAppSettingProperty(string key)
        {
            // Get the application configuration file.
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings.Remove(key);
    
            SaveConfigFile(config);
        }
    
        private static void SaveConfigFile(System.Configuration.Configuration config)
        {
            string sectionName = "appSettings";
    
            // Save the configuration file.
            config.Save(ConfigurationSaveMode.Modified);
    
            // Force a reload of the changed section. This  
            // makes the new values available for reading.
            ConfigurationManager.RefreshSection(sectionName);
    
            // Get the AppSettings section.
            AppSettingsSection appSettingSection =
              (AppSettingsSection)config.GetSection(sectionName);
    
            Console.WriteLine();
            Console.WriteLine("Using GetSection(string).");
            Console.WriteLine("AppSettings section:");
            Console.WriteLine(appSettingSection.SectionInformation.GetRawXml());
        }    
    }
    
    public void UpdateProperty(字符串键、字符串值)
    {
    Configuration config=ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    KeyValueConfigurationCollection appSettings=config.appSettings.Settings;
    //在退出之前更新savebeforexit
    config.AppSettings.Settings[key].Value=Value;
    控制台。写入(“…配置更新:键“+key+”,值:“+value+”);
    //保存文件
    config.Save(ConfigurationSaveMode.Modified);
    编写(“…保存的配置…”);
    //重新标记您修改的部分
    ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);
    写入(“…配置部分刷新…”);
    }
    公共无效ReadAppSettingsProperty()
    {
    尝试
    {
    var section=ConfigurationManager.GetSection(“应用程序设置”);
    //获取AppSettings部分。
    NameValueCollection appSettings=ConfigurationManager.appSettings;
    //获取AppSettings部分元素。
    Console.WriteLine();
    WriteLine(“使用AppSettings属性”);
    Console.WriteLine(“应用程序设置:”);
    如果(appSettings.Count==0)
    {
    WriteLine(“[ReadAppSettings:{0}]”,“AppSettings为空,请先使用GetSection命令。”);
    }
    对于(int i=0;i