如何从一个简单的应用程序中用.cs文件编译文件夹



我得到了.NET 2.0的应用程序。我想使用反射来收集类信息。但首先我需要编译文件夹中的.cs文件。如何从我的应用程序中?从我的应用程序中自动完成它非常重要。例如,我想有一个方法,我可以向它传递一个包含.cs文件的文件夹的路径,这个方法将为我编译所有.cs文件。

您可以这样做:

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;
}

您可以通过编程和命令行编译cs文件。要以编程方式完成此操作,您需要使用CSharpCodeProvider。您可以在此处找到有关该主题的更多信息:http://support.microsoft.com/kb/304655

相关内容

最新更新