Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Roslyn AddDocument to a project and Save this change to real solution file

Tags:

c#

roslyn

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.

enter image description here

like image 655
user2932893 Avatar asked Jan 17 '15 10:01

user2932893


2 Answers

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.

like image 68
SLaks Avatar answered Sep 18 '22 15:09

SLaks


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.

like image 28
Herr Kater Avatar answered Sep 22 '22 15:09

Herr Kater