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

时间:2012-12-23 04:17:43

标签: c# dynamic dll reference

我正在使用“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.

但是当我只是从Project> References> Add Reference中包含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

1 个答案:

答案 0 :(得分:1)

也许您需要为using命名空间

添加AnalogClockControl语句
sb.Append("using AnalogClockControl;\n"); // whatever the namespace is

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