一个不错读取Configuration文件的类,方便设置配置文件

本文介绍了一个用于读取、写入及删除XML配置文件中特定节点值的.NET类。该类扩展了System.Configuration.AppSettingsReader,并提供了GetValue、SetValue和removeElement等方法来方便地管理配置项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 类:Config.cs
  1 using  System;
  2 using  System.Xml;
  3 using  System.Reflection;
  4 using  System.Configuration;
  5 using  System.Windows.Forms;
  6
  7 namespace  XmlConfig
  8 {
  9    public class Config : System.Configuration.AppSettingsReader
 10    {
 11        private XmlNode node;
 12        private string _cfgFile;
 13
 14        public   string cfgFile
 15        {
 16            get    return _cfgFile; }
 17            set    { _cfgFile= Application.StartupPath + "//" + value; }
 18        }

 19
 20        public string GetValue (string key)
 21        {
 22            return Convert.ToString(GetValue(key, typeof(string)));
 23        }

 24
 25        public new object GetValue (string key, System.Type sType)
 26        {
 27            XmlDocument doc = new XmlDocument();
 28            object ro = String.Empty;
 29            loadDoc(doc);
 30            string sNode = key.Substring(0, key.LastIndexOf("//"));
 31            // retrieve the selected node
 32            try
 33            {
 34                node =  doc.SelectSingleNode(sNode);
 35                if( node != null )
 36                {
 37                    // Xpath selects element that contains the key
 38                    XmlElement targetElem= (XmlElement)node.SelectSingleNode(key) ;
 39                    if (targetElem!=null)
 40                    {
 41                        ro = targetElem.GetAttribute("value");
 42                    }

 43                }

 44                if (sType == typeof(string))
 45                    return Convert.ToString(ro);
 46                else
 47                    if (sType == typeof(bool))
 48                {
 49                    if (ro.Equals("True"|| ro.Equals("False"))
 50                        return Convert.ToBoolean(ro);
 51                    else
 52                        return false;
 53                }

 54                else
 55                    if (sType == typeof(int))
 56                    return Convert.ToInt32(ro);
 57                else
 58                    if (sType == typeof(double))
 59                    return Convert.ToDouble(ro);
 60                else
 61                    if (sType == typeof(DateTime))
 62                    return Convert.ToDateTime(ro);
 63                else
 64                    return Convert.ToString(ro);
 65            }

 66            catch
 67            {
 68                return String.Empty;
 69            }

 70        }

 71
 72        public bool SetValue (string key, string val)
 73        {
 74            XmlDocument doc = new XmlDocument();
 75            loadDoc(doc);
 76            try
 77            {
 78                // retrieve the target node
 79                string sNode = key.Substring(0, key.LastIndexOf("//"));
 80                node =  doc.SelectSingleNode(sNode);
 81                if( node == null )
 82                    return false;
 83                // Set element that contains the key
 84                XmlElement targetElem= (XmlElement) node.SelectSingleNode(key);
 85                if (targetElem!=null)
 86                {
 87                    // set new value
 88                    targetElem.SetAttribute("value", val);
 89                }

 90                    // create new element with key/value pair and add it
 91                else
 92                {
 93                    
 94                    sNode = key.Substring(key.LastIndexOf("//")+2);
 95                    
 96                    XmlElement entry = doc.CreateElement(sNode.Substring(0, sNode.IndexOf("[@")).Trim());
 97                    sNode =  sNode.Substring(sNode.IndexOf("'")+1);
 98                    
 99                    entry.SetAttribute("key", sNode.Substring(0, sNode.IndexOf("'")) );
100                    
101                    entry.SetAttribute("value", val);
102                    node.AppendChild(entry);
103                }

104                saveDoc(doc, this._cfgFile);
105                return true;
106            }

107            catch
108            {
109                return false;
110            }

111        }

112
113        private void saveDoc (XmlDocument doc, string docPath)
114        {
115            // save document
116            // choose to ignore if web.config since it may cause server sessions interruptions
117            if(  this._cfgFile.Equals("web.config") )
118                return;
119            else
120                try
121                {
122                    XmlTextWriter writer = new XmlTextWriter( docPath , null );
123                    writer.Formatting = Formatting.Indented;
124                    doc.WriteTo( writer );
125                    writer.Flush();
126                    writer.Close();
127                    return;
128                }

129                catch
130                {}
131        }

132
133        public bool removeElement (string key)
134        {
135            XmlDocument doc = new XmlDocument();
136            loadDoc(doc);
137            try
138            {
139                string sNode = key.Substring(0, key.LastIndexOf("//"));
140                // retrieve the appSettings node
141                node =  doc.SelectSingleNode(sNode);
142                if( node == null )
143                    return false;
144                // XPath select setting "add" element that contains this key to remove
145                XmlNode nd = node.SelectSingleNode(key);
146                node.RemoveChild(nd);
147                saveDoc(doc, this._cfgFile);
148                return true;
149            }

150            catch(Exception ex)
151            {
152                Console.WriteLine(ex.Message);
153                return false;
154            }

155        }

156
157        private void loadDoc ( XmlDocument doc )
158        {
159            // check for type of config file being requested
160            /*
161            if(  this._cfgFile.Equals("app.config"))
162            {
163                // use default app.config
164                this._cfgFile = ((Assembly.GetEntryAssembly()).GetName()).Name+".exe.config";
165            }
166            else
167                if(  this._cfgFile.Equals("web.config"))
168            {
169                // use server web.config
170                this._cfgFile = System.Web.HttpContext.Current.Server.MapPath("web.config");
171            }
172            */

173            // load the document
174            
175            doc.Load(this._cfgFile );
176        }

177
178    }

179}

180

使用:
取:
Config config = new Config();
config.cfgFile = "app.config";

txtCountry.Text =
config.GetValue("//appSettings//add[@key='CountryLoc']");
写:
config.SetValue("//appSettings//add[@key='" 
+ txtKey.Text + "']", txtValue.Text);

删除:
config.removeElement("//appSettings//add[@key='" + 
txtKey2.Text + "']");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值