user18623114
user18623114

Reputation:

What is wrong with this dynamic code execution?

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?

Upvotes: 0

Views: 118

Answers (1)

Fruchtzwerg
Fruchtzwerg

Reputation: 11399

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.

Upvotes: 1

Related Questions