当键值对不够时,我使用配置节,因为它们使用起来并不复杂(除非您需要复杂的部分):
定义自定义部分:
public class CustomSection : ConfigurationSection { [ConfigurationProperty("LastName", IsRequired = true, DefaultValue = "TEST")] public String LastName { get { return (String)base["LastName"]; } set { base["LastName"] = value; } } [ConfigurationProperty("FirstName", IsRequired = true, DefaultValue = "TEST")] public String FirstName { get { return (String)base["FirstName"]; } set { base["FirstName"] = value; } } public CustomSection() { } }
以编程方式创建您的部分(如果它尚不存在):
// Create a custom section. static void CreateSection() { try { CustomSection customSection; // Get the current configuration file. System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(@"ConfigurationTest.exe"); // Create the section entry // in theand the // related target section in . if (config.Sections["CustomSection"] == null) { customSection = new CustomSection(); config.Sections.Add("CustomSection", customSection); customSection.SectionInformation.ForceSave = true; config.Save(ConfigurationSaveMode.Full); } } catch (ConfigurationErrorsException err) { //manage exception - give feedback or whatever } }
在CustomSection定义之后,将为您创建实际的CustomSection:
现在检索您的部分属性:
CustomSection section = (CustomSection)ConfigurationManager.GetSection("CustomSection"); string lastName = section.LastName; string firstName = section.FirstName;
Mitchel Sell.. 12
如果我可以使用它,我将使用App.Config,但是,如果我需要更复杂的东西,我将使用自定义配置部分.是的,在开始时理解它是一件痛苦的事情,但是对于所有设置而言,统一的配置源和熟悉的配置值得花时间投资.
当键值对不够时,我使用配置节,因为它们使用起来并不复杂(除非您需要复杂的部分):
定义自定义部分:
public class CustomSection : ConfigurationSection { [ConfigurationProperty("LastName", IsRequired = true, DefaultValue = "TEST")] public String LastName { get { return (String)base["LastName"]; } set { base["LastName"] = value; } } [ConfigurationProperty("FirstName", IsRequired = true, DefaultValue = "TEST")] public String FirstName { get { return (String)base["FirstName"]; } set { base["FirstName"] = value; } } public CustomSection() { } }
以编程方式创建您的部分(如果它尚不存在):
// Create a custom section. static void CreateSection() { try { CustomSection customSection; // Get the current configuration file. System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(@"ConfigurationTest.exe"); // Create the section entry // in theand the // related target section in . if (config.Sections["CustomSection"] == null) { customSection = new CustomSection(); config.Sections.Add("CustomSection", customSection); customSection.SectionInformation.ForceSave = true; config.Save(ConfigurationSaveMode.Full); } } catch (ConfigurationErrorsException err) { //manage exception - give feedback or whatever } }
在CustomSection定义之后,将为您创建实际的CustomSection:
现在检索您的部分属性:
CustomSection section = (CustomSection)ConfigurationManager.GetSection("CustomSection"); string lastName = section.LastName; string firstName = section.FirstName;
如果我可以使用它,我将使用App.Config,但是,如果我需要更复杂的东西,我将使用自定义配置部分.是的,在开始时理解它是一件痛苦的事情,但是对于所有设置而言,统一的配置源和熟悉的配置值得花时间投资.