using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Reflection;
namespace CodeDOMDemo
{
class Program
{
static void Main(string[] args)
{
string doclib = Environment.CurrentDirectory;
string srccodePath = Path.Combine(doclib, "demo.cs");
CodeDomProvider provider = CodeDomProvider.CreateProvider("cs");
// 编译参数
CompilerParameters p = new CompilerParameters();
// 输出文件
p.OutputAssembly = "DemoLib.dll";
// 添加引用的程序集
// 其实我们这里用不上,只是作为演示
// mscorLib.dll是不用添加的,它是默认库
p.ReferencedAssemblies.Add("System.dll");
// 编译
CompilerResults res = provider.CompileAssemblyFromFile(p, srccodePath);
// 检查编译结果
if (res.Errors.Count == 0)
{
// 没有出错
Console.WriteLine("编译成功。");
// 获取刚刚编译的程序集信息
Assembly outputAss = res.CompiledAssembly;
// 全名
Console.WriteLine($"程序集全名:{outputAss.FullName}");
// 位置
Console.WriteLine($"程序集位置:{outputAss.Location}");
// 程序集中的类型
Type[] types = outputAss.GetTypes();
Console.WriteLine("----------------------\n类型列表:");
foreach (Type t in types)
{
Console.WriteLine(t.FullName);
}
}
else
{
// 如果编译出错
Console.WriteLine("发生错误,详见以下内容:");
foreach (CompilerError er in res.Errors)
{
Console.WriteLine($"行{er.Line},列{er.Column},错误号{er.ErrorNumber},错误信息:{er.ErrorText}");
}
}
Console.Read();
}
}
}