簡體   English   中英

Vsix(Visual Studio擴展)右鍵單擊文件的完整路徑

[英]Vsix (Visual Studio extension) full path of right-clicked file

我想檢索一個右鍵單擊文件的完整路徑(在Visual Studio 2017的編輯器內)。 在打開項目和/或解決方案時,我已經實現了以下代碼來檢索文件的路徑。

如果打開單個文件,則此實現不起作用。

場景:

  1. 開放VS(2017)
  2. 導航到文件->打開->文件。
  3. 右鍵單擊文件,然后單擊所需的上下文菜單。 (它調用IsSingleProjectItemSelection方法)。
  4. monitorSelection.GetCurrentSelection(out hierarchyPtr outboundPtr失敗,因為hierarchyPtr仍為IntPtr.Zero。

值不能為空。 參數名稱:pUnk

也許您知道在Visual Studio(2017)的編輯器中檢索右鍵單擊文件的完整路徑的解決方案?

先感謝您。

    if (!IsSingleProjectItemSelection(out hierarchy, out itemid)) return;
        // Get the file path
        string itemFullPath = null;
        ((IVsProject) hierarchy).GetMkDocument(itemid, out itemFullPath);
        var transformFileInfo = new FileInfo(itemFullPath);    
        string fullPath = itemFullPath.FullName;

public static bool IsSingleProjectItemSelection(out IVsHierarchy   hierarchy, out uint itemid)
{
    hierarchy = null;
    itemid = VSConstants.VSITEMID_NIL;
    int hr = VSConstants.S_OK;

    var monitorSelection = Package.GetGlobalService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection;
    var solution = Package.GetGlobalService(typeof(SVsSolution)) as IVsSolution;
    if (monitorSelection == null || solution == null)
    {
        return false;
    }

    IVsMultiItemSelect multiItemSelect = null;
    IntPtr hierarchyPtr = IntPtr.Zero;
    IntPtr selectionContainerPtr = IntPtr.Zero;

    try
    {
        hr = monitorSelection.GetCurrentSelection(out hierarchyPtr, out itemid, out multiItemSelect, out selectionContainerPtr);

        if (ErrorHandler.Failed(hr) || hierarchyPtr == IntPtr.Zero || itemid == VSConstants.VSITEMID_NIL)
        {
            // there is no selection
            return false;
        }

        // multiple items are selected
        if (multiItemSelect != null) return false;

        // there is a hierarchy root node selected, thus it is not a single item inside a project

        if (itemid == VSConstants.VSITEMID_ROOT) return false;

        hierarchy = Marshal.GetObjectForIUnknown(hierarchyPtr) as IVsHierarchy;
        if (hierarchy == null) return false;

        Guid guidProjectID = Guid.Empty;

        if (ErrorHandler.Failed(solution.GetGuidOfProject(hierarchy, out guidProjectID)))
        {
            return false; // hierarchy is not a project inside the Solution if it does not have a ProjectID Guid
        }

        // if we got this far then there is a single project item selected
        return true;
    }
    finally
    {
        if (selectionContainerPtr != IntPtr.Zero)
        {
            Marshal.Release(selectionContainerPtr);
        }

        if (hierarchyPtr != IntPtr.Zero)
        {
            Marshal.Release(hierarchyPtr);
        }
    }
}

DTE.ActiveDocument.FullName返回您右鍵單擊的文件的完整路徑。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM