我通过使用“CSharpCodeProvider”动态执行C#代码,然后编译代码并调用方法。我需要将某些DLL文件包含到编译器中,以便从该DLL中调用类。我使用的方法:在执行字符串时动态加载C#代码
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add(the path of the DLL File);
但调用方法时,我得到一个错误:
Could not load file or assembly or one of its dependencies. The system cannot find the file specified.
但是,当我刚包括从项目>参考>添加引用的DLL的代码中调用withed任何错误。任何人都可以告诉我如何在运行时动态添加引用以避免该错误?
下面是代码:
CSharpCodeProvider Code = new CSharpCodeProvider();
ICodeCompiler icc = Code.CreateCompiler();
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("system.dll");
cp.ReferencedAssemblies.Add("system.data.dll");
cp.ReferencedAssemblies.Add("system.windows.forms.dll");
cp.ReferencedAssemblies.Add(@"D:\AnalogClockControl.dll");
cp.CompilerOptions = "/t:library";
cp.GenerateInMemory = true;
StringBuilder sb = new StringBuilder("");
sb.Append("using System;\n");
sb.Append("using System.Data;\n");
sb.Append("using System.Windows.Forms;\n");
sb.Append("namespace CSCodeEvaler{ \n");
sb.Append("public class CSCodeEvaler{ \n");
sb.Append("public void test(){AnalogClockControl.AnalogClock _AnalogClock= new AnalogClockControl.AnalogClock();}\n");
sb.Append("} \n");
sb.Append("}\n");
CompilerResults cr = icc.CompileAssemblyFromSource(cp, sb.ToString());
if (cr.Errors.Count > 0)
{
return ; //"ERROR: " + cr.Errors[0].ErrorText
}
System.Reflection.Assembly a = cr.CompiledAssembly;
object o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler");
Type t = o.GetType();
MethodInfo mi = t.GetMethod("test");
object j = mi.Invoke(o, new object[] {}); // Here where I get the exception
也许你写错了路。你能告诉我们你的代码吗? – Mir
我的猜测是存在依赖性问题。尝试检查“Assembly loader exception”以获取更多信息。 – McGarnagle
谢谢你们的回应。 Eve:路径是正确的,否则如果我手动添加DLL,错误不会消失。我会在一分钟后发布代码.. dbaseman:请问我可以从哪里找到Assembly loader exception? – user1924025