从 IWpfTextView 获取非 cs 文件的文档路径

Art*_*iom 2 c# visual-studio vs-extensibility visual-studio-extensions

我想在VS的文本编辑器中添加一些按钮。在创建 ViewPort 管理器时的 ViewPortTextViewCreationListener 中,我想知道文档或其路径

public void TextViewCreated(IWpfTextView textView) {
    var result = _textDocumentFactoryService.TryGetTextDocument(TextView.TextBuffer, out ITextDocument textDocument);
    new ViewPortSwitcher(textView);
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用从 TextBufferITextDocumentFactoryService获取(请参阅此处的答案)。如果我打开 cs 文件,它可以正常工作。但如果我打开 cshtml 文件 TryGetTextDocument 返回 false。ITextDocument

Art*_*iom 5

最后,我在MSDN论坛找到了解决方案:

public static string GetPath(this IWpfTextView textView) {
    textView.TextBuffer.Properties.TryGetProperty(typeof(IVsTextBuffer), out IVsTextBuffer bufferAdapter);
    var persistFileFormat = bufferAdapter as IPersistFileFormat;

    if (persistFileFormat == null) {
        return null;
    }
    persistFileFormat.GetCurFile(out string filePath, out _);
    return filePath;
}
Run Code Online (Sandbox Code Playgroud)