Created
January 3, 2021 06:07
-
-
Save conikeec/59d5c2e3652dd49cf5fefd38113f4b31 to your computer and use it in GitHub Desktop.
Example of a CodeDom (predates Roslyn) based meta program
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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