2011年3月9日 星期三

ReadWriteAppConfig_VS2005

1.啟動 Visual Studio 2005
2.檔案/新增/專案/Visual C#專案類型/範本/主控台應用程式/ ReadWriteAppConfig
3.專案/加入新項目/XML 檔/名稱/App.config/加入
4.點選App.config編輯


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <appSettings>
      <add key="Key0" value="0" />
      <add key="Key1" value="1" />
      <add key="Key2" value="2" />
   </appSettings>
</configuration>
5.
點選Program.cs編輯
加入
using System.Configuration;
using System.Collections.Specialized;
完整程式碼:
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Collections.Specialized;

namespace ConConfig
{
    class Program
    {
        static void Main(string[] args)
        {
            string sAttr;

            // Read a particular key from the config file            
            sAttr = ConfigurationManager.AppSettings.Get("Key0");
            Console.WriteLine("The value of Key0: " + sAttr);

            // Read all the keys from the config file
            NameValueCollection sAll;
            sAll = ConfigurationManager.AppSettings;

            foreach (string s in sAll.AllKeys)
                Console.WriteLine("Key: " + s + " Value: " + sAll.Get(s));
           Console.ReadLine();
       }
    }
}
6.將參考加入System.Configuration.dll中:
專案/加入參考/.NET/System.Configuration/確定
否則出現
遺漏偵錯目標'C:\xxxxxxxxx',Visual Studio 無法啟動偵錯。請建置專案後再重試,或適當設定OutpatPath和AssemblyName屬性,以指向目標組件的正確位置。

沒有留言:

張貼留言