1. 首先建立一個winform解決方案
2. 與添加類檔案相同的方法添加設定檔,比如:右擊解決方案下的項目名稱—>添加—>建立項—>選擇 “應用程式設定檔”,.net預設檔案名稱為app.config,點擊確定
開啟檔案app.config,加入設定檔內容,比如:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Author Name" value="SOPPER" />
<add key="sqlconn" value="Data Source=(local);password=sa;user id=sa;Initial Catalog =db" />
</appSettings>
</configuration>
3. 右擊解決方案下的 引用—>添加引用,選擇 .net項下的System.Configuration 點擊確定
4. 在程式碼中加入using System.Configuration;最後就可以用下面的代碼來使用設定檔了
string appName =ConfigurationSettings.AppSettings["author Name"];
string strSql = ConfigurationManager.AppSettings["sqlconn"];//擷取設定檔裡自己設定的連接字串
//string strSql = System.Configuration.ConfigurationManager.ConnectionStrings[0].ConnectionString;//擷取系統預設的連接字串
label1.Text = appName;
label2.Text = strSql;
註:這裡的設定檔名稱是app.config,在產生應用程式時,會在應用程式的目錄下重建一個config檔案,檔案名稱與應用程式檔案名相同,尾碼是.config,(比如:winform.exe的設定檔名為winform.exe.config)此時的應用程式使用的設定檔就是與它同名的config檔案。