我是C#自定义配置的新手。
我想做一个简单的例子。我试过这个:https://stackoverflow.com/a/14890095/6121574但是,我像这样访问配置文件:https://stackoverflow.com/a/25806445/6121574
现在我得到系统配置中发生类型为"System.Configuration.ConfigurationErrorsException"的未处理异常.dll...无法加载文件或程序集 我的程序集
我的问题是:什么是 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);
}
}
}
}
我的应用配置
参数<?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>
type 属性的字符串的第一部分是类型本身,后跟包含该类型的程序集。
如果您的类型是 Company.Project.Configuration.Settings,并且保存在 Company.Project.dll 的程序集中,那么您将使用"Company.Project.Configuration.Settings, Company.Project"
如果项目名称为"我的"。它适用于此配置。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>