如何从库中访问自定义ConfigurationSection?

时间:2010-10-18 13:37:50

标签: c# configuration

早期,我在Console应用程序中定义了自定义部分,它工作正常。但现在我想将一些功能移到库中。但是,不幸的是,我做不到。因为现在我的自定义部分被定义为null。

简单的控制台应用程序包括下一个代码:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            NotificationsConfigurationSection section
  = NotificationsConfigurationSection.GetSection();
            string emailAddress = section.EmailAddress;
            Console.WriteLine(emailAddress);
            Console.Read();
        }
    }
}

具有自定义配置的文件位于单独的库中,包括下一个代码:

namespace ClassLibrary1
{
    public class NotificationsConfigurationSection : ConfigurationSection
    {
        private const string configPath = "cSharpConsultant/notifications";
        public static NotificationsConfigurationSection GetSection()
        {
            return (NotificationsConfigurationSection)
              ConfigurationManager.GetSection(configPath);
        }

        /*This regular expression only accepts a valid email address. */
        [RegexStringValidator(@"[\w._%+-]+@[\w.-]+\.\w{2,4}")]
        /*Here, we register our configuration property with an attribute. 
        Note that the default value is required if we use 
        the property validation attributes, which will unfortunately 
        attempt to validate the initial blank value if a default isn't found*/
        [ConfigurationProperty("emailAddress", DefaultValue = "Address@Domain.com")]
        public string EmailAddress
        {
            get { return (string)this["emailAddress"]; }
            set { this["emailAddress"] = value; }
        }
    }
}

在库的app.config中,我包含下一个节点:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="cSharpConsultant">
      <section name="notifications"
          type="ClassLibrary1.NotificationsConfigurationSection,
        ClassLibrary1"/>
    </sectionGroup>
  </configSections>
  <cSharpConsultant>
    <notifications emailAddress="NotifiedPerson@Domain.com"/>
  </cSharpConsultant>
</configuration>

有人能帮助我吗?

1 个答案:

答案 0 :(得分:0)

你的意思是你的app.config在库的项目中吗?

配置文件必须与可执行文件位于同一项目中。自定义部分的定义可以保留在库中,但配置文件本身必须与您要运行的项目位于同一个项目中。

在您的情况下,它应与ConsoleApplication1而不是ClassLibrary1

位于同一项目中