配置文件的动态修改

在 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 資料庫

posted @ 2008-08-27 11:04  华丽的空白  阅读(228)  评论(0编辑  收藏  举报