Home > Mobile >  What is wrong with this dynamic code execution?
What is wrong with this dynamic code execution?

Time:05-03

I have this code:

var code = @"public class Abc { public string Get() { return ""aaaaaaaaaa""; }}";
var options = new CompilerParameters();
options.GenerateExecutable = false;
options.GenerateInMemory = false;

var provider = new CSharpCodeProvider();
var compile = provider.CompileAssemblyFromSource(options, code);

var type = compile.CompiledAssembly.GetType("Abc");
var abc = Activator.CreateInstance(type);

var method = type.GetMethod("Get");
var result = method.Invoke(abc, null);
ut = result.ToString();

the variable code in this case gets executed correctly, but if I do something different like:

var code = @"using System; public class Abc { static string Get() { return System.DateTime.Now}}";

It does not get executed and gives me the following error: Could not load file or assembly 'file:///C:\Windows\TEMP\504kbl2w.dll' or one of its dependencies. The system cannot find the file specified

Why does it happen? How can I fix it?

CodePudding user response:

The code fails / can't be compiled because it contains three issues:

  1. The method needs to be public
  2. The return value is not a string like specified
  3. Missing semicolon in the method

Fix it like this to get it running:

var code = @"using System; public class Abc { public static string Get() { return System.DateTime.Now.ToString(); } }";

You should check the errors after compiling your code compile.Errors.

  •  Tags:  
  • c#
  • Related