代码之家  ›  专栏  ›  技术社区  ›  Dygestor

从另一个项目编译整个项目

  •  0
  • Dygestor  · 技术社区  · 11 年前

    我有一个Windows窗体应用程序,用于生成资源文件。我正在尝试向这个应用程序添加这样的功能,这将允许我将另一个Windows窗体应用程序编译为可执行文件,其中包含这些资源。然而,我一直在编译另一个Windows窗体项目部分。

    我试着跟随 this article ,到目前为止,我的代码如下:

    CompilerParameters parameters = new CompilerParameters();
    parameters.GenerateExecutable = true;
    parameters.IncludeDebugInformation = true;
    parameters.GenerateInMemory = false;
    //parameters.TreatWarningsAsErrors = true;
    parameters.WarningLevel = 3;
    parameters.CompilerOptions = "/optimize";
    parameters.OutputAssembly = "Program.exe";
    
    CSharpCodeProvider codeProvider = new CSharpCodeProvider();
    CompilerResults results = codeProvider.CompileAssemblyFromFile(parameters, new string[] { "Program.cs" });
    

    我不太确定,如果我做得正确(如果我应该编译Program.cs文件)。Program.cs文件如下所示:

    using System;
    using System.Windows.Forms;
    
    namespace example
    {
        static class Program
        {
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
        }
    }
    

    当我尝试用上面的代码编译它时,我得到了这个错误:

    Line number 16, Error Number: CS0246, 'The type or namespace name 'Form1' could not be found (are you missing a using directive or an assembly reference?)
    

    如果你们能帮我,我真的很感激,我从未从其他项目中编译过任何东西。

    1 回复  |  直到 11 年前
        1
  •  1
  •   infojolt    11 年前

    假设要编译的其他项目是project.csproj,请参考Microsoft.Build.Framework并使用以下代码:

    var globalProperty = new Dictionary<string, string> { { "Configuration", "Debug"}, { "Platform", "Any CPU" } };
    var buildParameters = new BuildParameters(new ProjectCollection()) { Loggers = new List<ILogger> { new ConsoleLogger() } };
    var buildRequest = new BuildRequestData(@"C:\example\project.csproj", globalProperty, "4.0", new[] {"Build" }, null);
    BuildResult buildResult = BuildManager.DefaultBuildManager.Build(buildParameters, buildRequest);
    

    或者您可以包装MsBuild.exe

    var p = new Process(); 
    p.StartInfo = new ProcessStartInfo(@"C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe");
    p.StartInfo.Arguments = @"C:\example\project.csproj";
    p.Start();