2012-11-05 88 views
1

我試圖創建app.config文件自定義欄目創建配置文件自定義欄目

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <configSections> 
    <section name="BlogSettings" type="ConsoleApplication1.BlogSettings, 
     ConsoleApplication1" /> 
    </configSections> 
    <BlogSettings 
    Price="10" 
    title="BLACKswastik" /> 
</configuration> 

C#代碼:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Configuration; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string title = BlogSettings.Settings.Title; 

      Console.WriteLine(title); 
      Console.ReadKey(); 
     } 
    } 

    public class BlogSettings : ConfigurationSection 
    { 
     private static BlogSettings settings 
      = ConfigurationManager.GetSection("BlogSettings") as BlogSettings; 

     public static BlogSettings Settings 
     { 
      get 
      { 
       return settings; 
      } 
     } 

     [ConfigurationProperty("Price" 
      , DefaultValue = 20 
      , IsRequired = false)] 
     [IntegerValidator(MinValue = 1 
      , MaxValue = 100)] 
     public int Price 
     { 
      get { return (int)this["Price"]; } 
      set { this["Price"] = value; } 
     } 


     [ConfigurationProperty("title" 
      , IsRequired = true)] 
     [StringValidator(InvalidCharacters = " [email protected]#$%^&*()[]{}/;’\"|\\" 
      , MinLength = 1 
      , MaxLength = 256)] 
     public string Title 
     { 
      get { return (string)this["title"]; } 
      set { this["title"] = value; } 
     } 
    } 
} 

但是當我運行這段代碼我得到這個錯誤:

The type initializer for 'ConsoleApplication1.BlogSettings' threw an exception.

請告訴我最新錯誤我在做什麼。

回答

3

你應該在CodeProject上看看Jon Rista關於.NET 2.0配置的三部分系列。

強烈推薦,寫得很好,非常有幫助!這將使您全面瞭解.NET配置系統。

菲爾哈克還有一個偉大的博客文章Three easy steps to a custom configuration section,可以讓您快速開始構建您自己的自定義配置部分。

要設計您自己的自定義部分,還有一個名爲Configuration Section Designer的便利工具(Visual Studio加載項),可以使創建自己的自定義部分變得非常容易和簡單,並使其構建所有必需的代碼以處理該自定義部分。

0

招了這一點的配置部分

<BlogSettings 
    Price="10" 
    title="BLACKswastik" /> 

的你犯了一個新的配置基準,因此它可以將自己的節點了。