XML配置文件的读取与修改
2016-06-30 08:34
344 查看
XML配置文件的读取与修改
<?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <!--串口数据--> <add key ="Port" value ="5"/> </appSettings> <!--数据库配置--> <connectionStrings> <add name="SMSSQL" connectionString="Data Source=192.168.0.8;Initial Catalog=SMS;User ID=sa;Password=sa" providerName="System.Data.SqlClient"/> </connectionStrings> </configuration>
一 . 读取配置文件
1. 用ConfigurationManager来读取
引用:System.Configuration;
public static string conString = ConfigurationManager.ConnectionStrings["SMSSQL"].ConnectionString;
2. 用XML中的XmlDocument
引用:System.Xml;
/// <summary>
/// 读取数据库配置文件
/// </summary>
/// <returns>无返回值</returns>
public static string readConn()
{
try
{
private static string configPath = System.Windows.Forms.Application.StartupPath + "\\App.config";
System.IO.FileInfo FileInfo = new System.IO.FileInfo(configPath);
//App.config文件是否存在
if (!FileInfo.Exists)
{
throw new ApplicationException("没有找到web.config配置文件!");
}
System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();
xmlDocument.Load(configPath);
string strConn = "";
foreach (System.Xml.XmlNode Node in xmlDocument["configuration"]["connectionStrings"])
{
if (Node.Name == "add")
{
if (Node.Attributes.GetNamedItem("name").Value == "SMSSQL")
{
strConn = Node.Attributes["connectionString"].Value;
}
}
}
return strConn;
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
二. 修改配置文件内
private bool UpdateWebConfig()
{
string configPath = System.Windows.Forms.Application.StartupPath + "\\App.config";
System.IO.FileInfo FileInfo = new System.IO.FileInfo(configPath);
if (!FileInfo.Exists) //不存在web.config文件
{
throw new ApplicationException("没有找到web.config配置文件!");
}
System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();
xmlDocument.Load(FileInfo.FullName);
bool FoundIt = false;
foreach (System.Xml.XmlNode Node in xmlDocument["configuration"]["connectionStrings"])
{
if (Node.Name == "add")
{
if (Node.Attributes.GetNamedItem("name").Value == "OASQL")
{
Node.Attributes.GetNamedItem("connectionString").Value = String.Format("Data Source={0};database={1};User ID={2};Password={3};Packet Size=4096;Pooling=true;Max Pool Size=100;Min Pool Size=1", _DataSource, _DBName, _UserID, _PassWord);
FoundIt = true;
break;
}
}
}
if (!FoundIt)
{
throw new ApplicationException("修改web.config配置文件失败!");
}
xmlDocument.Save(FileInfo.FullName);
return FoundIt;
相关文章推荐
- 使用composer安装第三方插件
- centos 磁盘分区
- 【Redis基础】Redis在项目中实战
- android 动画(5)ViewSwitcher
- 用xml做配置文件详解
- Cordova Geolocation以及baidu_map
- Codeforces Round #360(div2)
- 放大镜
- Anroid搭建一个局域网Web服务器
- Qt Quick里的图形效果:阴影(Drop Shadow)
- 没有自动联想补齐代码的解决办法
- 指尖下的js ——多触式web前端开发之一:对于Touch的处理
- 基本分段存储管理方式
- 安卓简单开发-安卓自带几种动画效果
- 14.1 threading--多线程
- 抽象方法不能是static或native或synchroniz
- 【伸展树splay学习小记】
- 注解开发--基础
- iOS 开发中的争议(二)
- 【bzoj1588】【HNOI2002】【营业额统计】【splay】