在执行字符串c#代码时动态加载程序集

本文关键字:动态 加载 程序集 代码 执行 字符串 | 更新日期: 2023-09-27 17:49:24

我通过使用"CSharpCodeProvider"动态执行c#代码,然后编译代码并调用方法。我需要包括一个特定的DLL文件的编译器,以便从该DLL调用类。我使用的方法是:

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时,调用的代码带有任何错误。有人能告诉我如何在运行时动态添加引用以避免该错误吗?

代码如下:

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

在执行字符串c#代码时动态加载程序集

也许您需要为AnalogClockControl命名空间添加using语句

sb.Append("using AnalogClockControl;'n"); // whatever the namespace is

编辑:没关系,如果需要的话,它根本不应该编译。