簡體   English   中英

如何通過文件名查找 ProjectItem

[英]How to find a ProjectItem by the file name

我正在為 Visual Studio 開發自定義工具。 該工具已分配給文件,在文件更改時我收到此文件的名稱,並且應該在項目中生成一些更改。 我需要通過接收到的文件名找到一個 ProjectItem。 我只找到了一個解決方案,它枚舉了解決方案的每個項目中的所有項目項。 但這似乎是一個巨大的解決方案。 有沒有辦法在不枚舉的情況下通過文件名獲取項目項?

這是我對 IVsSingleFileGenerator 的 Generate 方法的實現

public int Generate(string sourceFilePath, string sourceFileContent, string defaultNamespace, IntPtr[] outputFileContents, out uint output, IVsGeneratorProgress generateProgress)
{
    var dte = (EnvDTE.DTE)Package.GetGlobalService(typeof(EnvDTE.DTE));

    ProjectItem projectItem = null;

    foreach (Project project in dte.Solution.Projects)
    {
        foreach (ProjectItem item in project.ProjectItems)
        {
            var path = item.Properties.Item("FullPath").Value;
            if (sourceFilePath.Equals(path, StringComparison.OrdinalIgnoreCase))
            {
                projectItem = item;
            }
        }               
    }

    output = 0;
    outputFileContents[0] = IntPtr.Zero;

    return Microsoft.VisualStudio.VSConstants.S_OK;
}

我也在使用這個用戶友好的 DTE 世界來創建指南。 我沒有找到更好的解決方案。 基本上這些是我正在使用的方法:

迭代項目:

public static ProjectItem FindSolutionItemByName(DTE dte, string name, bool recursive)
{
    ProjectItem projectItem = null;
    foreach (Project project in dte.Solution.Projects)
    {
        projectItem = FindProjectItemInProject(project, name, recursive);

        if (projectItem != null)
        {
            break;
        }
    }
    return projectItem;
}

在單個項目中查找:

public static ProjectItem FindProjectItemInProject(Project project, string name, bool recursive)
{
    ProjectItem projectItem = null;

    if (project.Kind != Constants.vsProjectKindSolutionItems)
    {
        if (project.ProjectItems != null && project.ProjectItems.Count > 0)
        {
            projectItem = DteHelper.FindItemByName(project.ProjectItems, name, recursive);
        }
    }
    else
    {
        // if solution folder, one of its ProjectItems might be a real project
        foreach (ProjectItem item in project.ProjectItems)
        {
            Project realProject = item.Object as Project;

            if (realProject != null)
            {
                projectItem = FindProjectItemInProject(realProject, name, recursive);

                if (projectItem != null)
                {
                    break;
                }
            }
        }
    }

    return projectItem;
}

我正在使用更多片段的代碼可以在這里找到,作為新項目的指南。 搜索並獲取源代碼..

獲取 project.documents - 查找項目 - 使用 Linq 查詢文件

可能有點晚了,但使用 DTE2.Solution.FindProjectItem(fullPathofChangedFile);

暫無
暫無

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

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