当我运行代码时,我得到以下异常:
FileNotFoundException:无法加载文件或程序集"My"或其依赖项之一。系统找不到指定的文件
以下是我的app.config:<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>
下面是我的命名空间和类:
using System.Configuration;
using System.Linq;
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 new MyConfigInstanceElement this[string elementName]
{
get
{
return this.OfType<MyConfigInstanceElement>().FirstOrDefault(item => item.Name == elementName);
}
}
}
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; }
}
}
}
我正在尝试使用以下代码检索app.config:
MyConfigSection config = ConfigurationManager.GetSection("registerCompanies") as MyConfigSection;
Console.WriteLine(config.Instances["Honda Motors"].Code);
foreach (MyConfigInstanceElement e in config.Instances)
{
Console.WriteLine("Name: {0}, Code: {1}", e.Name, e.Code);
}
我认为它不起作用的唯一原因可能是因为我的命名空间my在另一个。cs文件ConfigSetup.cs中,我试图在另一个。cs文件中检索appconfig。
我不确定如何处理下面一行我的。MyCofigSection存在于ConfigSetup.cs和项目名称是FileManager,如果我需要包括它?下面一行给出了我上面提到的一个异常。
<section name="registerCompanies" type="My.MyConfigSection, My" />
我已经把type="My.MyConfigSection, My"
改成了type="My.MyConfigSection, File_Manager"
,效果很好,非常感谢