How to load solution in Roslyn?

Viewed 421

Here is my code that used to work:

MSBuildWorkspace msBuild = MSBuildWorkspace.Create();
Solution sln = await msBuild.OpenSolutionAsync(solutionPath);

but now I get:

int pr = sln.Projects.Count();//is 1 instead of 2.

and:

int docs = sln.Projects.First().Documents.Count();//is 0

Have they changed it again?

(If it matters, I need the Solution in order to iterate over fields etc. and use Renamer.RenameSymbolAsync .)

1 Answers

The way I did it was like so:

if (!MSBuildLocator.IsRegistered) MSBuildLocator.RegisterDefaults();
using (var w = MSBuildWorkspace.Create())
    {
        var sln = await w.OpenSolutionAsync(solutionPath);
    }

I believe the MSBuildLocator.RegisterDefaults() is the missing piece here. it ensures the correct msbuild path for your VS version. It might be that your environment path was correct, but then you installed another instance of VS and it's got confused somehow

Related