您的位置:首页 > 编程语言 > C#

C# 读写配置和xml文件

2011-04-13 12:14 656 查看
读取配置文件:

<?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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: