配置文件的动态修改

在 C# 中有一個重要的參數檔案:app.config ,我們要來談談此參數檔中關於連接資料庫的問題。當我們將程式製作成安裝片,在客戶端將程式安裝好,此檔案也會安裝的應用程式的目錄,但是檔案名稱會改 變。在開發者電腦是 app.config,在用戶的電腦會是 .config,什麼意思呢?例如你的程式主執行檔是 test.exe ,則此檔案會變成 test.exe.config ,所以後續我們要討論的程式將這對此檔案。

.config 檔案其實只是一個 XML 檔案,例如:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="test.Properties.Settings.ConnectionString" connectionString="data source=D:"Projects"Leap"NAS"LicenseData.sqlite"
providerName="System.Data.SQLite" />

</connectionStrings>
</configuration>

上面的設定中,connectionString 指向 D:"Projects"Leap"NAS"LicenseData.sqlite 這個資料庫,可是在用戶端,指向這個位置一定會出問題,所以程式要動態修改,範例如下:

XmlDocument doc = new XmlDocument();
string cn = "data source=" + Application.StartupPath + """LicenseData.sqlite";
string strFileName = AppDomain.CurrentDomain.BaseDirectory.ToString() + "test.exe.config";
doc.Load( strFileName );L
XmlNodeList nodes = doc.GetElementsByTagName( "add" );
for ( int i = 0; i < nodes.Count; i++ ) {
XmlAttribute att = nodes[i].Attributes["connectionString"];
att.Value = cn;
}
doc.Save(strFileName);

如此 connectionString 就會動態的指定到應用程式安裝路徑下的 LicenseData.sqlite 資料庫

转载于:https://www.cnblogs.com/zym23l/archive/2008/08/27/1277411.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值