这是我的代码,它加载一个dll文件并在xml中写入有关该文件的信息:
MyOptions ass = MyOptionsList[MyOptionsList.Count - 1];
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
StringWriter sw = new StringWriter();
XmlSerializer serializer = new XmlSerializer(ass.GetType(),
new Type[] { typeof(MyOptions) });
serializer.Serialize(sw, ass);
//more code writing in an xml file
AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve;
Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
return Assembly.LoadFrom(correctPath + ".dll");
}
问题发生在第serializer.Serialize(sw, ass);
行。内部异常表示我无法从一个dll转换为另一个dll。两个dll文件都具有相同的名称。一个在correctPath
,第二个在另一条路径上。如何解决这个问题?
MyOptions是一个类库项目,我正在加载的dll正在扩展。
答案 0 :(得分:2)
我只是尝试了下面没有问题,我认为你的问题必须在其他地方。
public class MyOptions
{
public int n;
}
static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
return Assembly.LoadFrom(@"C:\windwos\test.dll");
}
static void Main(string[] args)
{
MyOptions ass = new MyOptions();
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
StringWriter sw = new StringWriter();
XmlSerializer serializer = new XmlSerializer(ass.GetType(), new Type[] { typeof(MyOptions) });
serializer.Serialize(sw, ass);
//more code writing in an xml file
AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve;
}
请注意,不会调用事件代码。