C# 读写配置和xml文件
2011-04-13 12:14
656 查看
读取配置文件:
ConfigurationManager.AppSettings["time"].ToString();
写配置文件:
配置文件的路径需要使用完整路径名。
读写xml示例:
xml文件
读取xml
写入xml文件
<?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <add key="time" value="2011/4/13 11:58:25" /> </appSettings> </configuration>
ConfigurationManager.AppSettings["time"].ToString();
写配置文件:
配置文件的路径需要使用完整路径名。
XmlDocument doc=new XmlDocument(); //获得配置文件的全路径 string strFileName = AppDomain.CurrentDomain.BaseDirectory.ToString()+ "NotesAccess.exe.config"; doc.Load(strFileName); //找出名称为“add”的所有元素 XmlNodeList nodes=doc.GetElementsByTagName("add"); for(int i=0;i<nodes.Count;i++) { //获得将当前元素的key属性 XmlAttribute att=nodes[i].Attributes["key"]; //根据元素的第一个属性来判断当前的元素是不是目标元素 if (att.Value=="time") { //对目标元素中的第二个属性赋值 att=nodes[i].Attributes["value"]; att.Value = DateTime.Now.ToString(); ; break; } } //保存上面的修改 doc.Save(strFileName);}
读写xml示例:
xml文件
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE Font[ <!ELEMENT Font ANY> <!ELEMENT FontColor ANY> <!ELEMENT FontFamily ANY> <!ELEMENT FontSize ANY> <!ELEMENT FontStyle ANY> <!ATTLIST Font id ID #REQUIRED> ]> <Font id="font"> <!--字体颜色--> <FontColor>Blue</FontColor> <!--字体--> <FontFamily>微软雅黑</FontFamily> <!--字体大小--> <FontSize>14</FontSize> <!--字` 体样式(粗、斜体、下划线)--> <FontStyle>Bold</FontStyle> </Font>
读取xml
private static void Read() { try { XmlDocument doc = new XmlDocument(); // 获得配置文件的全路径 string strFileName = "Font.xml"; doc.Load(strFileName); XmlNode node = doc.GetElementById("font"); XmlNodeList nodes = node.ChildNodes; for (int i = 0; i < nodes.Count; i++) { if (nodes[i].NodeType == XmlNodeType.Element) { m_FontList[nodes[i].Name] = nodes[i].InnerText; } } } catch (Exception e) { throw e; } }
写入xml文件
private static void Write(string tagName, string value) { XmlDocument doc = new XmlDocument(); //获得配置文件的全路径 string strFileName = @"D:/chenb/SVN_Work/SMS/SMS/Font.xml"; doc.Load(strFileName); XmlNode node = doc.GetElementById("font"); XmlNodeList nodes = node.ChildNodes; for (int i = 0; i < nodes.Count; i++) { if(nodes[i].Name.Equals(tagName)) { nodes[i].InnerText = value; } } try { //保存上面的修改 doc.Save(strFileName); } catch (Exception e) { throw e; } }
相关文章推荐
- C# 读写XML配置文件
- c#通用配置文件读写类(xml,ini,json)
- C# XML配置文件读写类(用于程序配置保存)
- c# winform app.config xml 配置文件 读写操作
- c#通用配置文件读写类与格式转换(xml,ini,json)
- c#通用配置文件读写类与格式转换(xml,ini,json)
- C#读写xml文件
- VC使用tinyxml读写INI,cfg,XML配置文件
- C#实现XML文件读写
- Winform—C#读写config配置文件
- 用C#读写ini配置文件
- python读写csv_xml_json配置文件
- C# 读写XML文件
- C#读写xml文件
- C#使用单例模式类获取本地程序目录下XML文件中的配置信息
- 【转载】C#.NET 读写 INI配置文件
- java dom4j 读写XML配置文件
- 用C#读写ini配置文件(转自:http://www.cnblogs.com/zzyyll2/archive/2007/11/06/950584.html)
- C# 读写App.config配置文件的方法
- java读写xml和properties配置文件and Properties支持中文(转)