C# winform 添加設定檔

來源:互聯網
上載者:User

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檔案。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.