1
            string sln = path;

            MSBuildWorkspace workspace = MSBuildWorkspace.Create();
            Solution solution = workspace.OpenSolutionAsync(sln).Result;

            foreach (Project pro in solution.Projects)
            {
                
                foreach (Document documents in pro.Documents)
                {
                   
                    SyntaxNode rootNode = documents.GetSyntaxRootAsync().Result;
                    SemanticModel semanticModel = documents.GetSemanticModelAsync().Result;

                    IEnumerable<ClassDeclarationSyntax> myClasses = rootNode.DescendantNodes().OfType<ClassDeclarationSyntax>();
                    string pfad = documents.FilePath; .....

What I want to do is load a solution and its projects and the documents inside those projects then I want to get the path of those files. First 2 work but there are no documents being loaded. When executing this code, the second foreach is just being skipped completely. Debugging shows that documents is null.

I've seen other projects use this type of code but it doesn't work and I have no reason why. The dots mean there is more code but that part does actually work so I just cut it out. If someone has a clue, can you please add on to my code? Much appreciated!

Nope
  • 53
  • 7
  • hi, perhaps the data is missing, or step through with a debugger? – IronMan Dec 22 '20 at 23:48
  • Did that, sadly it just shows "null" for documents and skips the entire for loop. I dont think the data is missing tbh but I am not sure how roslyn accesses those files. Looking at other projects, some do exactly the same thing yet I can't seem to get the documents :/ – Nope Dec 23 '20 at 12:46
  • For debugging, subscribe to MSBuildWorkspace.WorkspaceFailed before calling OpenSolutionAsync; this will be raised if errors happen inside of the MSBuild loading process. – Jason Malinowski Jan 08 '21 at 20:13
  • Thanks for the tip. I got lots of stuff working now (and used the workspacefailed event etc). Well, many things were broken lol. Sorted the majority out! – Nope Jan 10 '21 at 00:02

1 Answers1

1

The possible reasons for pro.Documents returning null could be because of:

  1. .NET standard project is not supported by MSBuild Workspace. For more information, click here.
  2. Missing Nuget Packages

           a. Microsoft.Build

           b. Microsoft.Build.Utilities.Core

If none of the above solutions worked, then you can try debugging yourself by using MSBuildWorkspace.WorkspaceFailed event handler. Make sure that you subscribe to this event before calling OpenSolutionAsync method. Credits: Jason Malinowski