Roslyn Add a document to a project

淺唱寂寞╮ 提交于 2019-12-18 13:20:34

问题


I'm running roslyn ctp2

I am attempting to add a new html file to a project

IWorkspace workspace = Workspace.LoadSolution("MySolution.sln");
var originalSolution = workspace.CurrentSolution;
ISolution newSolution = originalSolution;
newSolution.GetProject(newSolution.ProjectIds.First())
                        .AddDocument("index.html", "<html></html>");
workspace.ApplyChanges(originalSolution, newSolution);

This results in no changes being written. I am trying to get the new html file to appear in VS


回答1:


There are two issues here:

  1. Roslyn ISolution, IProject, and IDocument objects are immutable, so in order to see changes you would need to create a new ISolution with the changes, then call Workspace.ApplyChanges().
  2. In Roslyn, IDocument objects are only created for files that are passed to the compiler. Another way of saying this is things that are part of the Compile ItemGroup in the project file. For other files (including html files), you should use the normal Visual Studio interfaces like IVsSolution.



回答2:


Workspaces are immutable. That means that any method that sounds like it's going to modify the workspace will instead be returning a new instance with the changes applied.

So you want something like:

IWorkspace workspace = Workspace.LoadSolution("MySolution.sln");
var originalSolution = workspace.CurrentSolution;
var project = originalSolution.GetProject(originalSolution.ProjectIds.First());
IDocument doc = project.AddDocument("index.html", "<html></html>");
workspace.ApplyChanges(originalSolution, doc.Project.Solution);

However, I'm not near a machine with Roslyn installed at the moment, so I can't guarantee this 100%.



来源:https://stackoverflow.com/questions/12367945/roslyn-add-a-document-to-a-project

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!