What is type in App.config custom section
我是C自定义配置的新手。
我想做一个简单的例子。我试过了:https://stackoverflow.com/a/14890095/6121574但是,我访问这样的配置文件:https://stackoverflow.com/a/25806445/6121574
现在我得到System.Configuration.dll中发生"System.Configuration.ConfigurationErrorException"类型的未处理异常。…无法加载文件或程序集my.assembly
我的问题是:app.config文件中的.assembly是什么?如何使我的代码工作?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace My { public class MyConfigSection : ConfigurationSection { [ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)] public MyConfigInstanceCollection Instances { get { return (MyConfigInstanceCollection)this[""]; } set { this[""] = value; } } } public class MyConfigInstanceCollection : ConfigurationElementCollection { protected override ConfigurationElement CreateNewElement() { return new MyConfigInstanceElement(); } protected override object GetElementKey(ConfigurationElement element) { //set to whatever Element Property you want to use for a key return ((MyConfigInstanceElement)element).Name; } } public class MyConfigInstanceElement : ConfigurationElement { //Make sure to set IsKey=true for property exposed as the GetElementKey above [ConfigurationProperty("name", IsKey = true, IsRequired = true)] public string Name { get { return (string)base["name"]; } set { base["name"] = value; } } [ConfigurationProperty("code", IsRequired = true)] public string Code { get { return (string)base["code"]; } set { base["code"] = value; } } } class Program { static void Main(string[] args) { var config = ConfigurationManager.GetSection("registerCompanies") as MyConfigSection; foreach (MyConfigInstanceElement e in config.Instances) { Console.WriteLine("Name: {0}, Code: {1}", e.Name, e.Code); } } } } |
我的App.CONFIG
1 2 3 4 5 6 7 8 9 10 11 | <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="registerCompanies" type="My.MyConfigSection, My.Assembly" /> </configSections> <registerCompanies> </registerCompanies> </configuration> |
如果项目名称为"我的"。它与这个配置一起工作。3小时后,我找到了解决方案:)
1 2 3 4 5 6 7 8 9 10 11 | <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="registerCompanies" type="My.MyConfigSection, My" /> </configSections> <registerCompanies> </registerCompanies> </configuration> |
类型属性的字符串的第一部分是类型本身,然后是包含该类型的程序集。
如果您的类型是company.project.configuration.settings,并且该类型保存在company.project.dll的程序集中,则将使用"company.project.configuration.settings,company.project"