Search code examples
c#configurationcompilationcodedomcsharpcodeprovider

C# - Compile c# code at runtime with custom configuration


I has a question, does CodeDom Compiler can compile c# code with custom configuration such as x64 bit or x86 bit.By default it compiles c# code to .exe with "Any CPU" configuration. Compiling c# code:

public static string BCS(string[] sources,string[] libs,string outPath,bool exef)
    {
        CSharpCodeProvider codeProvider = new CSharpCodeProvider();
        CompilerParameters parameters = new CompilerParameters(libs);
        parameters.GenerateExecutable = exef;
        parameters.OutputAssembly = outPath;
        CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, sources);

        if (results.Errors.Count > 0)
        {
            string errsText = "";
            foreach (CompilerError CompErr in results.Errors)
            {
                errsText = "("+CompErr.ErrorNumber +
                            ")Line " + CompErr.Line +
                            ",Column "+CompErr.Column +
                            ":"+CompErr.ErrorText + "" +
                            Environment.NewLine;
            }
            return errsText;
        }
        else
        {
            return "Success";
        }
    }

I think,youre understand my question,if not, leave a comment,i will give details.


Solution

  • Try to set CompilerOptions this way

    parameters.CompilerOptions = "-platform:anycpu32bitpreferred";

    using params from this link

    https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/platform-compiler-option

    P.S. CSharpCodeProvider uses csc.exe

    https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/command-line-building-with-csc-exe