【问题标题】:Loading Assembly Dynamically while executing string C# code在执行字符串 C# 代码时动态加载程序集
【发布时间】:2012-12-23 14:11:07
【问题描述】:

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

【问题讨论】:

  • 也许你写错了路径。你能告诉我们你的代码吗?
  • 我猜可能存在依赖问题。尝试检查“程序集加载程序异常”以获取更多信息。
  • 感谢大家的回复。 Eve:路径是正确的,否则如果我手动添加DLL,错误不会消失。我将在一分钟内发布代码.. dbaseman:你能告诉我从哪里可以找到 Assembly loader 异常吗?

标签: c# dynamic dll reference


【解决方案1】:

也许您需要为AnalogClockControl 命名空间添加一个using 状态

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

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

【讨论】:

  • 添加这一行不会做任何事情,因为当我定义实例时,我包含了完整的类名 AnalogClockControl.AnalogClock _AnalogClock= new AnalogClockControl.AnalogClock();无论如何,我试图添加这一行,我仍然有同样的错误。
猜你喜欢
  • 1970-01-01
  • 2016-07-12
  • 1970-01-01
  • 2016-10-24
  • 1970-01-01
  • 2010-10-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多