Get the path of the active document in Visual Studio

1.7k views Asked by At

I am writing a VSPackage for Visual Studio 2013 using C#.

I need a simple menu to be added to the Visual Studio menu bar. When clicking it, I want the current open (active) document in Visual Studio to be uploaded on a specific repository.

More Explanation: I want to create something like VisualSVN, when you install it a menu is added to the VS toolbar. When clicking the menu on the toolbar I want to upload my current open file in Visual Studio.

Question: How can I get the current document path in Visual Studio?

I have tried: Globals.ThisAddin.Application.ActiveDocument and DTE.ActiveDocument.

(Basically Globals and DTE don't have ThisAddin, ActiveDocuments for me.)

1

There are 1 answers

2
A-Sharabiani On BEST ANSWER

So I solved my problem by this:

DTE dte = (DTE)GetService(typeof(DTE));
string filePath = dte.ActiveDocument.FullName;

I also tried DTE2:

EnvDTE80.DTE2 dte2;
dte2 = (ENVDTE80.DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.12.0");
string filePath = dte2.ActivaDocument.FullName;

NOTE: When using DTE I get the current document in the Main Visual Studio (when running the code, another Visual Studio will be opened and you can see the your VSPackage when debugging.) The first method (DTE) gets the path to the active document in the newly opened VS. The second method (DTE2) gets the active document in the current Visual Studio --the one you are writing your code in.