Tôi là người mới bắt đầu với phần cấu hình trong C#
Tôi muốn tạo phần tùy chỉnh trong tệp cấu hình. Những gì tôi đã cố gắng sau khi googling là như sau
tập tin Config:
Phần Cấu hình tùy chỉnh trong App.config C#
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="MyCustomSections">
<section name="CustomSection" type="CustomSectionTest.CustomSection,CustomSection"/>
</sectionGroup>
</configSections>
<MyCustomSections>
<CustomSection key="Default"/>
</MyCustomSections>
</configuration>
CustomSection.cs
namespace CustomSectionTest
{
public class CustomSection : ConfigurationSection
{
[ConfigurationProperty("key", DefaultValue="Default", IsRequired = true)]
[StringValidator(InvalidCharacters = "[email protected]#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)]
public String Key
{
get { return this["key"].ToString(); }
set { this["key"] = value; }
}
}
}
Khi tôi sử dụng mã này để lấy Mục I gặp lỗi khi nói lỗi cấu hình.
var cf = (CustomSection)System.Configuration.ConfigurationManager.GetSection("CustomSection");
tôi đang thiếu gì?
Cảm ơn.
Sửa
Những gì tôi cần cuối cùng là
<CustomConfigSettings>
<Setting id="1">
<add key="Name" value="N"/>
<add key="Type" value="D"/>
</Setting>
<Setting id="2">
<add key="Name" value="O"/>
<add key="Type" value="E"/>
</Setting>
<Setting id="3">
<add key="Name" value="P"/>
<add key="Type" value="F"/>
</Setting>
</CustomConfigSettings>
Vui lòng xem lại các câu hỏi sau: http://stackoverflow.com/questions/3935331/how-to-implement-a-configurationsection-with-a-configurationelementcollection http://stackoverflow.com/questions/7983127/custom- cấu hình http://stackoverflow.com/questions/4738/using-configurationmanager-to-load-config-from-an-arbitrary-location – bytebuster