This should add a document.
public static void AddDoc()
{
var msBuild = MSBuildWorkspace.Create();
var sln = msBuild.OpenSolutionAsync
(@"D:\PanNiebieski\Documents\Visual Studio 14\Projects\WebApplication1"
+ @"\WebApplication1.sln").Result;
foreach (var p in sln.Projects)
{
p.AddDocument(Guid.NewGuid().ToString() + ".txt", "test");
var ok = msBuild.TryApplyChanges(sln);
Console.WriteLine(p.Name + ":" + ok);
}
Console.ReadKey();
}
Method "TryApplyChanges" returns true so that means document was added. Then again when I check solution nothing like that exist. I have the same problem with adding references to a project.
The question is how I can save change like adding a document to a real project. Do I miss something. Many question in StackOverflow about adding references to a project said that this simply doesn't work. Does method "AddDocument" also does nothing?
This method says this action is supported. I am confused.
Roslyn's entire workspace & syntax APIs are immutable.
p.AddDocument
creates a new Project
and Solution
(which is returned in the Project
property of the returned Document
), which you're ignoring.
This one should do the thing:
IWorkspace workspace = Workspace.LoadSolution(@"..\RoslynTest.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);
source: http://www.wenda.io/questions/982766/roslyn-add-a-document-to-a-project.html
UPDATE: it is not applicable anymore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With