Question

I have a Windows Forms application, which I use to generate resource files. I'm trying to add such functionality to this application, that would allow me to compile another Windows Forms application into an executable, that would have these resources included. However, I'm stuck on that compile another Windows Forms project part.

I tried to follow this article, my code so far looks like this:

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

I'm not exactly sure, if I'm doing this correctly (if I should compile Program.cs file). Program.cs file looks like this:

using System;
using System.Windows.Forms;

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

And when I try to compile it with the code above, I get this error:

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?)

I'd really appreciate if you guys could help me out, I've never compiled anything from another project.

Was it helpful?

Solution

Assuming the other project you want to compile is project.csproj, reference Microsoft.Build.Framework and use this code:

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

Or you could just wrap the 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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top