c# - Creating a Visual Studio menu command to get current active file path
问题描述
I am trying to create a 2017 VS extension with a button command that will display the file path of the current active file. I have followed this https://docs.microsoft.com/en-us/visualstudio/extensibility/extensibility-hello-world?view=vs-2017#prerequisites and have already created the extention but I cannot seem to get the file path of the active file.
解决方案
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 = transformFileInfo.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);
}
}
}
推荐阅读
- r - 如何使用主函数检索 R 中每个主成分的观察分数
- php - php循环中数据库的样式输出
- ios - 'pod init' 返回:不允许操作 - getcwd (Errno::EPERM)
- python - 如何在多个条件下使用 np.where
- node.js - Next.js + Graphql 解耦架构中如何转发用户会话?
- typescript - 使用类验证器验证字符串文字类型
- django - send_mail() 因 privateemail.com 而失败
- java - 无法解决符号 RecyclerViewActions / RecyclerViewMatcher
- django - 从表格而不是数据库报告实验室打印值
- ffmpeg - 如何使用带有 FFMPEG 的 drawtext 增加文本的行高?