Config文件的操作

 





    
public class NSection : ConfigurationSection {

        
public NSection() 

        

        }


        [ConfigurationProperty(
"id")]

        
public int ID

        
{

            
get return (int)this["id"]; }

            
set this["id"= value; }

        }


 

        [ConfigurationProperty(
"name")]

        
public string Name

        
{

            
get return this["name"].ToString(); }

            
set this["name"= value; }

        }


 

        
public override string ToString()

        
{

            StringBuilder sb 
= new StringBuilder();

            sb.AppendFormat(
"id = {0};name = {1}", ID, Name);

            
return sb.ToString();

        }


    }

添加
NSection section 
= new NSection();

        section.ID 
= 1;

        section.Name 
= "Test";

        Configuration config 
= WebConfigurationManager.OpenWebConfiguration("~");

        config.Sections.Remove(
"nSection");

        config.Sections.Add(
"nSection", section);

        config.Save();

    }
修改


Configuration config1 
= WebConfigurationManager.OpenWebConfiguration("~");

        NSection section1 
= config1.GetSection("nSection"as NSection;

        section1.ID 
= 2;

        section1.Name 
= "Test2";

        config1.Save();
查看
Configuration config 
= WebConfigurationManager.OpenWebConfiguration("~");
        AppSettingsSection appSection 
= (AppSettingsSection)config.GetSection("appSettings");
        
string[] Keys = appSection.Settings.AllKeys;
        
for (int i = 0; i < Keys.Length; i++)
        
{
            Response.Write(Keys[i] 
+ ":" + appSection.Settings[Keys[i]].Value + "<br>");
        }


        ConnectionStringSettingsCollection connectionStrings 
= WebConfigurationManager.ConnectionStrings;
        
for (int i = 0; i < connectionStrings.Count; i++)
        
{
            Response.Write(
string.Format("Name:{0}:Conn{1}Pro{2}<br>", connectionStrings[i].Name, connectionStrings[i].ConnectionString, connectionStrings[i].ProviderName));
        }


        
//删除appSettings节点中的元素
        appSection.Settings.Remove("addkey1");
        
//修改appSettings节点中的元素
        appSection.Settings["addkey2"].Value = "Modify key2's value";
        config.Save();



  
<appSettings>
    
<add key="ConfigPath" value="~/Config/" />
    
<add key="UploadSavePath" value="~/uploads/" />
    
<add key="EncryptMethod" value="1" />
    
<add key="AppTimeOut" value="0" />
    
<add key="CookieName" value="UserLogin" />
    
<add key="MultiDomainName" value="" />
    
<add key="EnableDomains" value="" />
    
<add key="staticFileExt" value=".aspx" />
    
<add key="EnableLog" value="true" />
    
<add key="addkey2" value="Modify key2's value" />
  
</appSettings>
  
 
  
<connectionStrings>
    
<add name="Default" providerName="SqlClient" connectionString="server=FENGYUN;uid=sa;pwd=110110;database=CMS;"/>
  
</connectionStrings>


posted @ 2007-04-29 15:19  李占卫  阅读(462)  评论(0编辑  收藏  举报