Note that there are some explanatory texts on larger screens.

plurals
  1. POIncluding C# files when compiling programmatically from a string
    text
    copied!<p>I was previously exporting CodeDOM CompilationUnits to files, and then reading those files back in to compile them using a CSharpCodeProvider. Today I refactored the code so that the CodeDOM is exported to a String:</p> <pre><code>public static string compileToString(CodeCompileUnit cu){ // Generate the code with the C# code provider. CSharpCodeProvider provider = new CSharpCodeProvider(); using (StringWriter sw = new StringWriter()) { IndentedTextWriter tw = new IndentedTextWriter(sw, " "); // Generate source code using the code provider. provider.GenerateCodeFromCompileUnit(cu, tw, new CodeGeneratorOptions()); tw.Close(); return sw.ToString (); } } </code></pre> <p>And then changed the compilation so that it uses CompileFromSource:</p> <pre><code>public static Assembly BuildAssemblyFromString(string code){ Microsoft.CSharp.CSharpCodeProvider provider = new CSharpCodeProvider(); ICodeCompiler compiler = provider.CreateCompiler(); CompilerParameters compilerparams = new CompilerParameters(); compilerparams.GenerateExecutable = false; compilerparams.GenerateInMemory = true; compilerparams.CompilerOptions = "/nowarn:162"; string[] files = new string[]{"TemplateAesthetic.cs"}; CompilerResults results = compiler.CompileAssemblyFromSource(compilerparams, code); if (results.Errors.HasErrors) { StringBuilder errors = new StringBuilder("Compiler Errors :\r\n"); foreach (CompilerError error in results.Errors ) { errors.AppendFormat("Line {0},{1}\t: {2}\n", error.Line, error.Column, error.ErrorText); Debug.Log (error.ErrorText); } } else { return results.CompiledAssembly; } return null; } </code></pre> <p>Thanks to Maarten for noticing: the problem is that I need to include a real file (TemplateAesthetic.cs) in the compilation process, but this compilation happens from a string. Can you do a mixed compilation in this way using CompileAssemblyFromSource?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload