简体   繁体   English

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

[英]Loading Assembly Dynamically while executing string C# code

I am executing C# code dynamically by using "CSharpCodeProvider" then compile the code and invoke the method. 我正在使用“ CSharpCodeProvider”动态执行C#代码,然后编译代码并调用该方法。 I need to include a certain DLL files to the compiler in order to call classes from that DLL. 我需要在编译器中包含某些DLL文件,以便从该DLL调用类。 I am using the method: 我正在使用的方法:

CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add(the path of the DLL File);

But when invoking the method, I get an error : 但是当调用该方法时,出现错误:

Could not load file or assembly or one of its dependencies. The system cannot find the file specified.

But when I just include the DLL from Project>References>Add Reference , the code invoked withed any error. 但是,当我仅从Project> References> Add Reference中包含DLL时,调用的代码会出现任何错误。 Can anyone tell me how to add the reference dynamically on run-time to avoid that error? 谁能告诉我如何在运行时动态添加引用以避免该错误?

Here is the code : 这是代码:

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

Maybe you need to add a using statament for AnalogClockControl namespace 也许您需要为AnalogClockControl名称空间添加using语句

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

EDIT: never mind, that should not compile at all if it was required. 编辑:没关系,如果需要的话,那根本不应该编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM