zoukankan      html  css  js  c++  java
  • 运行时修改config文件

    运行时修改config文件

    【IT168知识库】
     


    首先要添加对System.Configuration的引用。

    修改App.config的数据库连接字符串:

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

                config.ConnectionStrings.ConnectionStrings[
    "ConnectionString"].ConnectionString = String.Format(
                    
    "server={0};uid={1};pwd={2};database={3}",
                    cboServer.Text,
                    txtUser.Text.Trim(),
                    txtPassword.Text.Trim(),
                    cboDatabase.Text);

                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection(config.ConnectionStrings.SectionInformation.Name);

    config文件中内容如下:
    <configuration>
        
    <connectionStrings>
            
    <add name="ConnectionString" connectionString="server=(local);uid=sa;pwd=sa;database=MYDB" providerName="System.Data.SqlClient"/>
            
    <add name="ConnectionString1" connectionString="server=(local);uid=sa;pwd=123;database=MYDB" providerName="System.Data.SqlClient"/>
        
    </connectionStrings>
    </configuration>

    如果是Web.config要使用这句打开config文件:
    Configuration config = WebConfigurationManager.OpenWebConfiguration("~");

    不过修改web.config后,会造成Session被清除。



    也可以使用对象模型的方式去修改:
    config文件如下:
    <configuration>
        
    <configSections>
    <section name="MyClass" type="MyCommponents.MyClass, MyCommponents"/>
    </configSections>
    <MyClass MyProperty="0"/>
    </configuration>

    MyCommponents签名的话,也要相应添加Version,Culture,PublicKeyToken。

    这样写config文件后,在MyCommponents程序集中定义一个MyClass类

    namespace MyCommponents
    {
        
    public class MyClass : ConfigurationSection
        
    {
            
    public MyClass() { }

            [ConfigurationProperty(
    "MyProperty")]
            
    public Int32 MyProperty
            
    {
                
    get return (int)this["MyProperty"]; }
                
    set this["MyProperty"= value; }
            }

        }

    }

    修改代码如下:
    Configuration config = WebConfigurationManager.OpenWebConfiguration("~");

                MyClass configData 
    = config.GetSection("MyClass"as MyClass;
    configData.MyProperty 
    = 1;
    config.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection(configData.SectionInformation.Name);
  • 相关阅读:
    关于 __proto__和prototype的一些理解
    使用siege进行web压力测试
    Access denied for user 'root'@'localhost' (using password: YES)
    博客搬家来咯
    Permutation Transformer【Splay】
    Prime Independence 【LightOJ
    Power Sockets【CF 1469F】【线段树+贪心】
    A Bit Similar【CF 1469E】【unordered_map+bitset】
    brz的树【牛客练习赛72 F】【虚树+dfs序可持久化线段树+树上差分】
    CCA的期望【牛客练习赛74】【数学】
  • 原文地址:https://www.cnblogs.com/kingkoo/p/1126106.html
Copyright © 2011-2022 走看看