Search code examples
c#compiler-constructionroslynformatter

How to use Formatter.Format(SyntaxNode,Workspace) in roslyn?


I'm using roslyn version 1.3.2 from nuget in my project. First I tried to use these codes to format my code:

var root = CSharpSyntaxTree.ParseText("filepath").GetRoot();
var workspace=MSBuildWorkspace.Create();
node=Formatter.Format(root,workspace);

And it throw IOException when executing MSBuildWorkspace.Create():

Could not load file or assembly 'Microsoft.Build, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

Then I tried to install BuildTools from Nuget as this question said: MSBuildWorkspace.Create() throws exception

And I get lots of errors,so I uninstall it and remove all its files. But when I try to call MSBuildWorkspace.Create() it won't throw a IOException. I have no idea how that works.

Unfortunately, the SyntaxNode still won't be formatted after I called Formatter.Format even if there is no exception or warning or error at all.

One more thing,I can easily format some code in a standalone console application without buildtools or IOException. They are using same codes. Why that's incompatible with my project?

So what's the correct way to use that,better with out the BuildTools nuget package?


Solution

  • The workspace needs to actually contain the syntax root (in a project). You can't just pass an empty workspace.

    Unless you actually want to load a csproj or sln, you don't need MSBuild at all; you can create an AdHocWorkspace, add a project, add your syntax tree, and format that.