Visit and modify all documents in a solution with Roslyn

I want to view all the documents in each project in this solution using Roslyn.

This is the code I have now:

var msWorkspace = MSBuildWorkspace.Create(); var solution = await msWorkspace.OpenSolutionAsync(solutionPath); foreach (var project in solution.Projects) { foreach (var document in project.Documents) { if (document.SourceCodeKind != SourceCodeKind.Regular) continue; var doc = document; foreach (var rewriter in rewriters) { doc = await rewriter.Rewrite(doc); } if (doc != document) { Console.WriteLine("changed {0}",doc.Name); //save result //the solution is now changed and the next document to be processed will belong to the old solution msWorkspace.TryApplyChanges(doc.Project.Solution); } } } 

The problem here is that since Roslyn is pretty much unchanged. After the first "msWorkspace.TryApplyChanges" the solution and the document are now replaced with new versions.

So, the next iteration will still go over the old versions. Is there any way to do this in Roslin's idiomatic style? Or do I need to resort to some kind of hacking? T / t>

+5
source share
1 answer

This solution, posted in the Roslyn gitter chat, does the trick and solves the problem.

 var solution = await msWorkspace.OpenSolutionAsync(solutionPath); foreach (var projectId in solution.ProjectIds) { var project = solution.GetProject(projectId); foreach (var documentId in project.DocumentIds) { Document document = project.GetDocument(documentId); if (document.SourceCodeKind != SourceCodeKind.Regular) continue; var doc = document; foreach (var rewriter in rewriters) { doc = await rewriter.Rewrite(doc); } project = doc.Project; } solution = project.Solution; } msWorkspace.TryApplyChanges(solution); 

in this case, the changes are no longer discarded between iterations, since everything is based on the result of the last iteration. (that is, documents and projects are retrieved using an identifier, not from a counter that looks at the original structure)

+7
source

All Articles