Search code examples
c#visual-studiovisual-studio-extensionsvsixextensibility

In C# VSIX, How to get current file name along with its relative path which is currently being editing?


I am working on a VSIX project, where I want to get the current file name and path (relative to the project) which is being edited in the VS IDE (or in an experimental window)? How can I do that?

I tried following code:

var currentDocInfo = this._textDocumentFactoryService.TryGetTextDocument(this.view.TextBuffer, out this.TextDocument);            

if (currentDocInfo)
{
    string test = this.TextDocument.FilePath;
    MessageBox.Show(test);
}
else
{
    //MessageBox.Show("Nothingg!");
}

This code is returning absolute path of currently opened file. And I need to get path relative to the current project/solution. If I am able to get even the name of solution, I will find the relative path of the project.

If I add code: System.IO.Path.GetDirectoryName(dte.Solution.FullName); It will return the path details of my TextAdornment class (a class, managing the editor tasks by getting installed with my whole plugin, Here I am writing dte.ActiveDocument.FullName; code). But I want file details of the file which is opened in my experimental window.


Solution

  • If you want to get the file name of the current open text editor in your experimental window

    DTE dte = Package.GetGlobalService(typeof(SDTE)) as DTE; string docName = dte.ActiveDocument.Name;

    EDIT

    Example for a menu button, returns the current file name of the open document in the experimental visual studio instance, if the menu button is clicked

    private void Execute(object sender, EventArgs e)
        {
            /// Get Open Documents
            string docName = GetActiveTextEditor();
            if (docName == null) return;
    
        }
    
    internal static string GetActiveTextEditor()
        {
            DTE dte = Package.GetGlobalService(typeof(SDTE)) as DTE;
            string docName = dte.ActiveDocument.Name;
            return docName;
        }