using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Xml;
using System.Reflection;

namespace Walter.K.Wang.Config
{
    
/// <summary>
    
/// 讀寫配置文件操作類
    
/// </summary>

    public class Config
    
{
        
/// <summary>
        
/// 讀配置文件
        
/// </summary>
        
/// <param name="key">關鍵字</param>
        
/// <returns></returns>

        public string ReadConfig(string key)
        
{
            
return ConfigurationManager.AppSettings[key].ToString();
        }


        
/// <summary>
        
///  寫配置文件
        
/// </summary>
        
/// <param name="key">關鍵字</param>
        
/// <param name="value"></param>

        public void WriteConfig(string key,string value)
        
{
            XmlDocument doc 
= new XmlDocument();
            
//創建DLL文件
            doc.Load(Assembly.GetEntryAssembly().Location + ".config");
            
//程序中片段碼
            XmlNode node = doc.SelectSingleNode("//appSettings");
            
if (node == null)
                
throw new InvalidOperationException("沒有找到AppSettings接點.");
            
try
            
{
                XmlElement elem 
= (XmlElement)node.SelectSingleNode(string.Format("//add[@key='{0}']", key));
                
if (elem != null)
                
{
                    elem.SetAttribute(
"value", value);
                }

                
else
                
{
                    elem 
= doc.CreateElement("add");
                    elem.SetAttribute(
"key", key);
                    elem.SetAttribute(
"value", value);
                    node.AppendChild(elem);
                }

                doc.Save(Assembly.GetEntryAssembly().Location 
+ ".config");
            }

            
catch(Exception Err)
            
{
                
throw new Exception(Err.Message);
            }

        }

    }

}

 
posted on 2007-09-17 19:51  wkjs  阅读(158)  评论(0编辑  收藏  举报