2012-06-17 112 views
2

我建立一个CodeCompileUnit和下面的代码输出C#源代码文件,一个.dll,我可以从组件获得一个实例:CompileAssemblyFromDom抛出FileNotFoundException异常

TextWriter tw = new IndentedTextWriter(new StreamWriter(filePath + ".cs", false), " "); 
provider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions()); 
tw.Close(); 

CompilerParameters cp = new CompilerParameters { GenerateInMemory = true, GenerateExecutable = false}; 
cp.ReferencedAssemblies.Add("MyProgram.exe"); 
cp.OutputAssembly = filePath + ".dll"; 
CompilerResults cr = provider.CompileAssemblyFromFile(cp, filePath + ".cs"); 

MyType instance = (MyType)Activator.CreateInstance(cr.CompiledAssembly.GetTypes()[0]); 

到目前为止好。现在我想避免生成这些文件:

CompilerParameters cp = new CompilerParameters { GenerateInMemory = true, GenerateExecutable = false}; 
cp.ReferencedAssemblies.Add("MyProgram.exe"); 
//cp.OutputAssembly = filePath + ".dll"; 
CompileResults cr = provider.CompileAssemblyFromDom(cp, compileUnit); 

这引发FileNotFoundException。它在我的\ temp文件夹中查找x32savit.dll(或类似的),但它不在那里。如果我取消注释OutputAssembly,它将失败,但在该路径上。

回答

4

原来是命名空间的错误。有一个很好的例子here

添加以下代码在调试时非常有用。

string errorText = String.Empty; 
    foreach (CompilerError compilerError in compilerResults.Errors) 
     errorText += compilerError + "\n";