2017-10-17 185 views
0

我需要將任何C#或VB.NET項目編譯爲.NetModule。我有下面的示例代碼,其中發出DLL,需要一些幫助來修改以下從.csproj得到.NetModules與Roslyn編譯模塊

在此先感謝。

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

回答

1

我相信你正在尋找CompilationOptions.OutputKind特別OutputKind.NetModule

東西類似於以下應該工作:

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

現在,你應該能夠得到一個編譯和發射爲你通常會。

0

下列固定的問題

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