MSBuild构建工作空间,解决project.Documents.Count()=0的问题

代码(来源https://www.dropbox.com/sh/6bog8n56iosg1z5/AABi-MBuqpuB1_OwqJ3wZFKya?dl=0&file_subpath=%2FRoslyn_Walker&preview=Roslyn_Walker.zip):

  1 using System;
  2 using System.IO;
  3 using System.Linq;
  4 using System.Threading.Tasks;
  5 using Microsoft.CodeAnalysis;
  6 using Microsoft.CodeAnalysis.CSharp;
  7 using Microsoft.CodeAnalysis.CSharp.Syntax;
  8 using Microsoft.CodeAnalysis.MSBuild;
  9 using Microsoft.Build.Locator;
 10 using System.Collections.Generic;
 11 namespace Test_roslyn_project
 12 {
 13     class Program
 14     {
 15         static void Main(string[] args)
 16         {
 17             try
 18             {
 19                 //MSBuildLocator.RegisterDefaults();
 20 
 21                 // Attempt to set the version of MSBuild.
 22                 var instance = MSBuildLocator.QueryVisualStudioInstances().Single();
 23                 Console.WriteLine($"Using MSBuild at '{instance.MSBuildPath}' to load projects.");
 24 
 25                 // NOTE: Be sure to register an instance with the MSBuildLocator 
 26                 //       before calling MSBuildWorkspace.Create()
 27                 //       otherwise, MSBuildWorkspace won't MEF compose.
 28                 MSBuildLocator.RegisterInstance(instance);
 29 
 30                 //Change this path as per required.
 31                 string[] projectsToParse =
 32                     Directory.GetFiles(@"E:\VS2017\WorkSpace\Learn\Student_mangent\Student_mangent", "*.csproj", SearchOption.AllDirectories);
 33 
 34                 Console.WriteLine("Projects to Parse: " + projectsToParse);
 35                 foreach (var currentFile in projectsToParse)
 36                 {
 37                     Console.WriteLine("Project: " + currentFile);
 38                     BrowseProjectsToParse(currentFile);
 39                 }
 40 
 41             }
 42             catch (Exception ex)
 43             {
 44                 Console.WriteLine(ex.StackTrace);
 45             }
 46         }
 47 
 48         private static void BrowseProjectsToParse(string projectPath)
 49         {
 50             try
 51             {
 52                 using (var workspace = MSBuildWorkspace.Create())
 53                 {
 54                     workspace.LoadMetadataForReferencedProjects = true;
 55                     // Print message for WorkspaceFailed event to help diagnosing project load failures.
 56                     workspace.WorkspaceFailed += (o, e) => Console.WriteLine(e.Diagnostic.Message);
 57 
 58                     Project currentProject = workspace.OpenProjectAsync(projectPath).Result;
 59                     
 60                     Console.WriteLine("Project Name: " + currentProject.Name + " .Project Document Count: " + currentProject.Documents.Count());
 61                     foreach(var doc in currentProject.Documents)
 62                     {
 63                         Console.WriteLine(doc.Name);
 64                     }
 65                     if (currentProject.Documents.Any())
 66                     {
 67                         foreach (var document in currentProject.Documents)
 68                         {
 69                             SemanticModel sementicModel = document.GetSemanticModelAsync().Result;
 70                         }
 71                     }
 72                 }
 73             }
 74             catch (Exception ex)
 75             {
 76                 Console.WriteLine("BrowseProjectsToParse: " + ex.StackTrace);
 77             }
 78         }
 79 
 80         private static void WorkSpaceFailed(object sender, WorkspaceDiagnosticEventArgs e)
 81         {
 82             Console.WriteLine("WorkSpaceFailed: " + e.Diagnostic.Message);
 83         }
 84 
 85         public static bool AnalyzeProject(Project project, string changedFilesOptionsFilePath = null)
 86         {
 87             Console.WriteLine("Project Name: " + project.Name + " .Project Document Count: " + project.Documents.Count());
 88 
 89             if (project.Language == "C#")
 90             {
 91                 if (project.Documents.Any()
 92                     && project.Documents.Any(x => x.Name.ToLower().EndsWith(".cs")))
 93                 {
 94                     Project projectInstance = project;
 95 
 96                     RemoveDuplicateProjectReferences(ref projectInstance);
 97 
 98                     foreach (var document in projectInstance.Documents)
 99                     {
100                         AnalyzeDocument(document);
101                     }
102                 }
103             }
104             else
105             {
106                 return false;
107             }
108 
109             return true;
110         }
111 
112         private static void RemoveDuplicateProjectReferences(ref Project projectInstance)
113         {
114             var allProjectReference = projectInstance.AllProjectReferences;
115             var distinctProjectCount = allProjectReference.Distinct().Count();
116 
117             if (allProjectReference.Count > distinctProjectCount)
118             {
119                 List<ProjectReference> uniqueProjectReferencs = new List<ProjectReference>();
120                 List<ProjectReference> duplicateProeProjectReferencs = new List<ProjectReference>();
121 
122                 foreach (var projectRef in projectInstance.AllProjectReferences)
123                 {
124                     if (!uniqueProjectReferencs.Contains(projectRef))
125                         uniqueProjectReferencs.Add(projectRef);
126                     else
127                         duplicateProeProjectReferencs.Add(projectRef);
128                 }
129 
130                 foreach (var dupProjRef in duplicateProeProjectReferencs)
131                 {
132                     projectInstance = projectInstance.RemoveProjectReference(dupProjRef);
133                 }
134             }
135         }
136 
137 
138         private static void AnalyzeDocument(Document document)
139         {
140             try
141             {
142                 SyntaxNode decendendNodes = document.GetSyntaxRootAsync().Result;
143 
144                 try
145                 {
146                     SemanticModel sementicModel = document.GetSemanticModelAsync().Result;
147 
148                 }
149                 catch (Exception ex)
150                 {
151                     if (ex.InnerException != null) Console.WriteLine(ex.InnerException.ToString());
152                     Console.WriteLine(ex.StackTrace.ToString());
153                 }
154             }
155             catch (Exception e)
156             {
157                 Console.WriteLine(e.StackTrace);
158             }
159         }
160     }
161 }

 

posted @ 2021-07-22 15:07  博二爷  阅读(107)  评论(0编辑  收藏  举报