Skip to content

Instantly share code, notes, and snippets.

@rezanid
Last active January 21, 2025 22:03
Show Gist options
  • Select an option

  • Save rezanid/deaf313bad190cd64649261c8453db60 to your computer and use it in GitHub Desktop.

Select an option

Save rezanid/deaf313bad190cd64649261c8453db60 to your computer and use it in GitHub Desktop.
How to get the Document object in Visual Studio extensions
// The wrong way:
private GetVisualStudioDocument(SnapshotPoint triggerLocation)
{
// Get the VisualStudioWorkspace service
var componentModel = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel));
var workspace = componentModel.GetService<VisualStudioWorkspace>();
// Retrieve the document associated with the trigger location
var documentId = workspace.CurrentSolution.GetDocumentId(triggerLocation.Snapshot.TextBuffer.AsTextContainer());
if (documentId == null) return CompletionContext.Empty;
return (document == null) ? CompletionContext.Empty : workspace.CurrentSolution.GetDocument(documentId);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment