我想
1>创建一个C#模板代码。
2>动态编译。
3>存储已编译的程序集。
4>然后其他一些过程将执行组装。
在大多数步骤中,我能够使用here的建议来做到这一点。
模板C#代码将使用Newtonsoft.Json
,因此我想将其添加为CompilerParams
中的引用。
为简洁起见,我删除了一些代码
static void CompileAndRun(string[] code)
{
CompilerParameters CompilerParams = new CompilerParameters();
string outputDirectory = Directory.getcurrentDirectory();
CompilerParams.GenerateInmemory = true;
CompilerParams.TreatWarningsAsErrors = false;
CompilerParams.GenerateExecutable = false;
CompilerParams.CompilerOptions = "/optimize";
string[] references = { "System.dll","Newtonsoft.Json" };
CompilerParams.ReferencedAssemblies.AddRange(references );
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerResults compile = provider.CompileAssemblyFromSource(CompilerParams,code);
if (compile.Errors.HasErrors)
{
string text = "Compile error: ";
foreach (CompilerError ce in compile.Errors)
{
text += "rn" + ce.ToString();
}
throw new Exception(text);
}
// removed for bravity purpose
}
但这会引发编译错误System.Exception: 'Compile error: error CS0006: Metadata file 'Newtonsoft.Json' could not be found'
请注意,正在执行此代码的项目引用了Newtonsoft.Json
程序集
如何添加对Newtonsoft.Json
程序集的引用?