c# - 如何从简单的应用程序编译带有 .cs 文件的文件夹

问题描述 投票:0回答:2

我收到了 .NET 2.0 的申请。我想使用反射来收集类信息。但首先我需要编译文件夹中的 .cs 文件。我如何从我的应用程序中做到这一点?从我的应用程序自动执行此操作非常重要。例如,我想要一个方法,我可以将路径传递给包含 .cs 文件的文件夹,并且此方法将为我编译所有 .cs 文件。

c# asp.net compilation
2个回答
1
投票
你可以这样做:

using Microsoft.CSharp; using System.CodeDom.Compiler; using System.CodeDom; public static Assembly CreateFromCSFiles(string pathName) { CSharpCodeProvider csCompiler = new CSharpCodeProvider(); CompilerParameters compilerParams = new CompilerParameters(); compilerParams.GenerateInMemory = true; // here you must add all the references you need. // I don't know whether you know all of them, but you have to get them // someway, otherwise it can't work compilerParams.ReferencedAssemblies.Add("system.dll"); compilerParams.ReferencedAssemblies.Add("system.Data.dll"); compilerParams.ReferencedAssemblies.Add("system.Windows.Forms.dll"); compilerParams.ReferencedAssemblies.Add("system.Drawing.dll"); compilerParams.ReferencedAssemblies.Add("system.Xml.dll"); DirectoryInfo csDir = new DirectoryInfo(pathName); FileInfo[] files = csDir.GetFiles(); string[] csPaths = new string[files.Length]; foreach (int i = 0; i < csPaths.Length; i++) csPaths[i] = files[i].FullName; CompilerResults result = csCompiler.CompileAssemblyFromFile(compilerParams, csPaths); if (result.Errors.HasErrors) return null; return result.CompiledAssembly; }
    

0
投票
您可以通过编程方式和命令行编译 cs 文件。 要以编程方式执行此操作,您需要使用

CSharpCodeProvider

 您可以在此处找到有关该主题的更多信息:
http://support.microsoft.com/kb/304655

© www.soinside.com 2019 - 2024. All rights reserved.