簡體   English   中英

c#-如何通過簡單的應用程序使用.cs文件編譯文件夾

[英]c# - how to compile folder with .cs files from a simple application

我得到了.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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM