我正在使用 CodeDom 创建新的 .cs 文件,稍后想使用 CSharpCodeProvider 编译/运行它们,但在引用方面遇到了一些问题。
代码如下:
var provider = new CSharpCodeProvider();
var compilerparams = new CompilerParameters(
new[]
{
"First.dll",
"Second.dll"
})
{
GenerateExecutable = false,
GenerateInMemory = true
};
CompilerResults results = provider.CompileAssemblyFromFile(compilerparams, _path);
if (!results.Errors.HasErrors)
return results.CompiledAssembly;
var 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());
“First.dll”和“Second.dll”存在于与我生成的 .cs 文件相同的文件夹中,如果我直接运行它,我会出错。如果我将它们移动到我的项目 bin 目录中,它工作正常,但我宁愿将它们分开。
是否可以为“First.dll”和“Second.dll”设置绝对路径或包含我所有引用的目录的路径而不是将它们移动到我的 bin 目录?
我尝试将 CompilerParameters 更改为绝对路径,但这没有帮助。
最佳答案
我找到了解决此问题的新解决方案。我没有在内存中生成,而是设置了一个输出路径并返回了这个路径。所以稍后当我想使用它时,我用 Assembly.LoadFrom() 加载它(它将使用同一目录中的所有引用的 dll)。
示例代码,
如何生成程序集:
public string CompileCode()
{
var provider = new CSharpCodeProvider();
var outputPath = Path.Combine(Path.GetDirectoryName(_path), "temp.dll");
var compilerparams = new CompilerParameters(
new[]
{
@"D:\path\to\referenced\dll",
@"D:\path\to\referenced\dll2"
}, outputPath);
CompilerResults results = provider.CompileAssemblyFromFile(compilerparams, _path);
var i = results.PathToAssembly;
if (!results.Errors.HasErrors)
return i;
var 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());
}
加载它:
Assembly assembly = Assembly.LoadFrom(path);
//Do stuff with assembly
关于c# - 可以为 CSharpCodeProvider 中的引用设置绝对路径吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31076217/