0

I need to compile any C# or VB.NET project to .NetModule. I have following sample code which emits DLLs, Need some help to modify following to get .NetModules out from .csproj

Thanks in advance.

// Required Microsoft.CodeAnalysis 1.3.0    
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                //Please copy provide a path to a .csproj
                CompileProject(@"C:\WebGoat\WebGoat.NET.csproj", @"C:\tempout").Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        async static Task<string> CompileProject(string projectFilePath, string outputFolderPath)
        {
            using (var workspace = MSBuildWorkspace.Create())
            {
                var project = workspace.OpenProjectAsync(projectFilePath).Result;
                await Emit(project, outputFolderPath);
                return Path.GetFileName(project.OutputFilePath);
            }
        }

        async static Task Emit(Project project, string outputFolderPath)
        {
            Directory.CreateDirectory(outputFolderPath);
            var compilation = await project.GetCompilationAsync();
            var outputFilePath = Path.Combine(outputFolderPath, Path.GetFileName(project.OutputFilePath));
            var pdbFilePath = Path.ChangeExtension(outputFilePath, "pdb");
            var compilationStatus = compilation.Emit(outputFilePath, pdbPath: pdbFilePath);

            if (!compilationStatus.Success)
            {
                Console.WriteLine("Failed.");
            }
            else
            {
                Console.WriteLine("Pass.");
            }
        }
Bandara
  • 780
  • 8
  • 29

2 Answers2

1

I believe you're looking for CompilationOptions.OutputKind and specifically OutputKind.NetModule.

Something similar to the following should work:

var project = workspace.OpenProjectAsync(projectFilePath).Result;
var options = project.CompilationOptions;
var netModuleOptions = options.WithOutputKind(OutputKind.NetModule);
var projectWithOptions = project.WithCompilationOptions(netModuleOptions);

Now you should be able to get a compilation and emit it as you normally would.

JoshVarty
  • 9,066
  • 4
  • 52
  • 80
0

Following fixed the issue

   var project = workspace.OpenProjectAsync(projectFilePath).Result;
   var options = project.CompilationOptions;
   options = options.WithOutputKind(OutputKind.NetModule).WithPlatform(Platform.AnyCpu);

   project = project.WithCompilationOptions(options);
   var moduleCompilation = await project.GetCompilationAsync();
Bandara
  • 780
  • 8
  • 29