Search code examples
c#compiler-errorscompiler-constructioncsc

Releasing .exe file from input string as code


I have a question. How to release .exe file from string input?

I want to compile to exe Hello World C# example. Here is my code:

var code = input.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

var provider = CodeDomProvider.CreateProvider("CSharp");
string exeName = string.Format("test.exe", Environment.CurrentDirectory);
var parameters = new CompilerParameters
{
    GenerateExecutable = true,
    OutputAssembly = exeName,
    GenerateInMemory = false,
    TreatWarningsAsErrors = false
};
parameters.ReferencedAssemblies.Add("System.dll");

var compilerResults = provider.CompileAssemblyFromSource(parameters, code);

if (compilerResults.Errors.Count > 0)
    //Error

else
    //Succes, file saved int Debug folder (exe file)

From code above, i want to get code as string, then i make string[] array (each array's record is next line of code). Then, i want to save that exe file into Debug Folder.

But for, now, from compilerResults.Errors i get 32 errors that looks like this:

enter image description here

I belive that is something about mapping this function to c# language. Any ideas, what im doing wrong?

EDIT:

code array looks like this:

enter image description here


Solution

  • CodeDomProvider.CreateAssemblyFromSource expects each string in the array to be a source file - you're providing a single line per element.

    In other words, you don't need your call to Split to start with. Just use:

    var code = new[] { input };