簡體   English   中英

在執行字符串C#代碼時動態加載程序集

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

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

也許您需要為AnalogClockControl名稱空間添加using語句

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

編輯:沒關系,如果需要的話,那根本不應該編譯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM