1. 程式人生 > >C# 修改Web.Config配置檔案

C# 修改Web.Config配置檔案

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;

 

public partial class _CS_admin_Default_st_sys : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //呼叫
        ConfigurationOperator cfgOper = new ConfigurationOperator();
        cfgOper.SetAppSetting("name", "value");//新增一個節點,如果有就修改
        cfgOper.Save();
        cfgOper.Dispose();
    }
    

}


/// 
/// ConfigurationOperator 的摘要說明
/// 
public class ConfigurationOperator : IDisposable
{
    private Configuration config;
    public ConfigurationOperator()
        : this(HttpContext.Current.Request.ApplicationPath)
    {

    }
    public ConfigurationOperator(string path)
    {
        config = WebConfigurationManager.OpenWebConfiguration(path);
    }
    /// 
    /// 設定應用程式配置節點,如果已經存在此節點,則會修改該節點的值,否則新增此節點
    /// 
    /// 節點名稱 
    /// 節點值 
    public void SetAppSetting(string key, string value)
    {
        AppSettingsSection appSetting = (AppSettingsSection)config.GetSection("appSettings");
        if (appSetting.Settings[key] == null)//如果不存在此節點,則新增
        {
            appSetting.Settings.Add(key, value);
        }
        else//如果存在此節點,則修改
        {
            appSetting.Settings[key].Value = value;
        }
    }
    /// 
    /// 設定資料庫連線字串節點,如果不存在此節點,則會新增此節點及對應的值,存在則修改
    /// 
    /// 節點名稱 
    /// 節點值 
    public void SetConnectionString(string key, string connectionString)
    {
        ConnectionStringsSection connectionSetting = (ConnectionStringsSection)config.GetSection("connectionStrings");
        if (connectionSetting.ConnectionStrings[key] == null)//如果不存在此節點,則新增
        {
            ConnectionStringSettings connectionStringSettings = new ConnectionStringSettings(key, connectionString);
            connectionSetting.ConnectionStrings.Add(connectionStringSettings);
        }
        else//如果存在此節點,則修改
        {
            connectionSetting.ConnectionStrings[key].ConnectionString = connectionString;
        }
    }
    /// 
    /// 儲存所作的修改
    /// 
    public void Save()
    {
        config.Save();
        config = null;
    }
    public void Dispose()
    {
        if (config != null)
        {
            config.Save();
        }
    }
}