【问题标题】:Compile assembly in runtime and save dll in a folder在运行时编译程序集并将 dll 保存在文件夹中
【发布时间】:2014-01-27 14:40:25
【问题描述】:

这是我的代码:

Microsoft.CSharp.CSharpCodeProvider provider = new CSharpCodeProvider();
ICodeCompiler compiler = provider.CreateCompiler();
CompilerParameters compilerparams = new CompilerParameters();
compilerparams.GenerateInMemory = false;
CompilerResults results = compiler.CompileAssemblyFromSource(compilerparams, code);

if (results.Errors.HasErrors)
{
    StringBuilder errors = new StringBuilder("Compiler Errors :\r\n");
    foreach (CompilerError error in results.Errors )
    {
        errors.AppendFormat("Line {0},{1}\t: {2}\n", 
               error.Line, error.Column, error.ErrorText);
    }
    throw new Exception(errors.ToString());
}
else
{
    return results.CompiledAssembly;
}

如何将创建的 dll 保存到我自己的特定文件夹中?当我调试时,不知何故,程序集位置位于“AppData/Local/Temp/”文件夹中。

【问题讨论】:

    标签: c# compilation runtime .net-assembly


    【解决方案1】:

    您可以使用CompilerParametersOutputAssembly 属性来设置输出程序集的名称(路径)。 从你的例子:

    ...
    CompilerParameters compilerparams = new CompilerParameters();
    compilerparams.GenerateInMemory = false;
    
    compilerparams.OutputAssembly = "OutputAssembly.dll";
    
    CompilerResults results = compiler.CompileAssemblyFromSource(compilerparams, code);
    ...
    

    【讨论】:

    • 我会接受这个答案,但最终还是会出现在 'AppData/Local/Temp/' 中。
    • @dausdashsan 这很奇怪。我已经测试了代码,它确实将程序集放在了 OutputAssembly 属性指向的任何地方。程序集在AppData/Local/Temp/ 中结束的唯一方法是将一个空/空字符串传递给OutputAssembly 属性。
    【解决方案2】:

    使用 OutputAssembly 属性,您可以只指定程序集名称。程序集将在当前目录中创建。 如果您需要指定完整路径,则必须以这种方式设置编译器选项字符串:

    System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
     parameters.GenerateExecutable = false;
     parameters.CompilerOptions = " /out:C:\\Temp\\" + outputAssemblyFile;
    

    here,这个属性可以设置很多选项。 如果设置 CompilerOptions,则 OutputAssembly 属性将被忽略。

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2011-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-19
      • 1970-01-01
      相关资源
      最近更新 更多