Exemple #1
0
        public static Document GetDocument(this VisualStudioWorkspace workspace, string filePath, Guid projGuid)
        {
            var projectToGuidMap = (ImmutableDictionary <ProjectId, Guid>)projectToGuidMapField.GetValue(workspace);
            var sln = workspace.CurrentSolution;

            var candidateId = sln
                              .GetDocumentIdsWithFilePath(filePath)
                              // VS will create multiple `ProjectId`s for projects with multiple target frameworks.
                              // We simply take the first one we find.
                              .FirstOrDefault(candidateId => projectToGuidMap.GetValueOrDefault(candidateId.ProjectId) == projGuid)
                              ?? throw new InvalidOperationException($"File {filePath} (project: {projGuid}) not found in solution {sln.FilePath}.");

            var currentContextId = workspace.GetDocumentIdInCurrentContext(candidateId);

            return(sln.GetDocument(currentContextId)
                   ?? throw new InvalidOperationException($"Document {currentContextId} not found in solution {sln.FilePath}."));
        }
        // Code adapted from Microsoft.VisualStudio.LanguageServices.CodeLens.CodeLensCallbackListener.TryGetDocument()
        public static Document?GetDocument(this VisualStudioWorkspace workspace, string filePath, Guid projGuid)
        {
            var projectToGuidMap = (ImmutableDictionary <ProjectId, Guid>)_projectToGuidMapField.GetValue(workspace);
            var sln = workspace.CurrentSolution;

            var candidateId = sln
                              .GetDocumentIdsWithFilePath(filePath)
                              // VS will create multiple `ProjectId`s for projects with multiple target frameworks.
                              // We simply take the first one we find.
                              .FirstOrDefault(candidateId => projectToGuidMap.GetValueOrDefault(candidateId.ProjectId) == projGuid)
            ;

            if (candidateId == null)
            {
                return(null);
            }

            var currentContextId = workspace.GetDocumentIdInCurrentContext(candidateId);

            return(sln.GetDocument(currentContextId));
        }