我是C#自定义配置的新手。
我想做一个简单的例子。 我试过这个:https://stackoverflow.com/a/14890095/6121574 但是,我这样访问配置文件:https://stackoverflow.com/a/25806445/6121574
现在我明白了 System.Configuration.dll中发生未处理的“System.Configuration.ConfigurationErrorsException”类型异常 ...无法加载文件或程序集My.Assembly
我的问题是:App.config文件中的My.Assembly是什么?如何使我的代码工作?
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
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="registerCompanies"
type="My.MyConfigSection, My.Assembly" />
</configSections>
<registerCompanies>
<add name="Tata Motors" code="Tata"/>
<add name="Honda Motors" code="Honda"/>
</registerCompanies>
</configuration>
答案 0 :(得分:0)
type属性的字符串的第一部分是类型本身,然后是包含该类型的程序集。
如果您的类型是Company.Project.Configuration.Settings,并且它保存在Company.Project.dll的程序集中,那么您将使用“Company.Project.Configuration.Settings,Company.Project”
答案 1 :(得分:0)
如果项目名称是&#34;我的&#34;。它适用于此配置。 3个小时后,我找到了一个解决方案:)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="registerCompanies"
type="My.MyConfigSection, My" />
</configSections>
<registerCompanies>
<add name="Tata Motors" code="Tata"/>
<add name="Honda Motors" code="Honda"/>
</registerCompanies>
</configuration>