Skip to content

Instantly share code, notes, and snippets.

@conikeec
Created January 3, 2021 06:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save conikeec/59d5c2e3652dd49cf5fefd38113f4b31 to your computer and use it in GitHub Desktop.
Save conikeec/59d5c2e3652dd49cf5fefd38113f4b31 to your computer and use it in GitHub Desktop.
Example of a CodeDom (predates Roslyn) based meta program
public static Assembly Compile(string[] sources, bool isDebug, string tempDir, params AssemblyName[] referencedAssemblies)
{
var codeProvider = new CSharpCodeProvider(new Dictionary<string, string> {{"CompilerVersion", "v4.0"}});
var assemblyReferences = new[]
{
"System.dll",
"System.Core.dll",
"mscorlib.dll"
}
.Union(from ass in referencedAssemblies
select new Uri(ass.CodeBase).LocalPath)
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToArray();
var parameters = new CompilerParameters
{
GenerateInMemory = true,
GenerateExecutable = true,
IncludeDebugInformation = isDebug,
OutputAssembly = Path.Combine(tempDir, "generatedassembly.dll")
};
parameters.ReferencedAssemblies.AddRange(assemblyReferences);
if (tempDir.Length > 0) parameters.TempFiles = new TempFileCollection(tempDir);
parameters.TempFiles.KeepFiles = isDebug;
var compilerResults = codeProvider.CompileAssemblyFromSource(parameters, sources);
if (compilerResults.Errors.HasErrors)
{
var message = string.Join("\r\n", compilerResults.Errors);
throw new ApplicationException(message);
}
return compilerResults.CompiledAssembly;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment