0

Is it somehow possible to have access to the ITextBuffer instance of the document that is being analyzed by a Roslyn diagnostic analyzer in Visual Studio. Or at least the filename, so that I can retrieve the ITextBuffer myself?

For more information on how to write a custom code analyzer for c#, see: https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/tutorials/how-to-write-csharp-analyzer-code-fix

TWT
  • 2,511
  • 1
  • 23
  • 37
  • Its probably better to describe the actual problem you are trying to get the buffer for to solve, as maybe there is a better solution to that problem, than trying to get the buffer – Sam Holder Jun 25 '19 at 09:24

2 Answers2

2

In general, the infrastructure around analyzers was created to allow them to run outside of Visual Studio (eg. from commandline or as part of a CI build system). This is why there aren't many easy ways to interop between Roslyn and Visual Studio. However there are a few different extension methods that can help you bridge the gap between Visual Studio and Roslyn.

I believe you need to:

  1. Add the NugetPackage with Install-Package Microsoft.CodeAnalysis.EditorFeatures.Text
  2. Add the using using Microsoft.CodeAnalysis.Text; to your analyzer

If you have access to a Document you can use .TryGetText(out SourceText) to retrieve the SourceText for a document.

Then you can use the extension method FindCorrespondingEditorTextSnapshot to get an ITextSnapshot.

My knowledge here is a little shakey but I'm not sure if you can get an ITextBuffer because your analyzer will often be running when no editor is opened for a given file so no ITextBuffer has been created for it.

JoshVarty
  • 9,066
  • 4
  • 52
  • 80
2

The SyntaxTree has a property FilePath, as does the Document, which if not the empty string, would be the path to the file.

No idea how to go from that to the buffer. But it’s also unclear why you would want the buffer...

jmoreno
  • 12,752
  • 4
  • 60
  • 91