Visual Studio macro: Find files that aren't included in the project?

后端 未结 4 1976
情深已故
情深已故 2020-12-03 09:00

I\'d like to write a macro to crawl through the files in my project directory and find files that aren\'t included in the project.

In playing around with the DTE ob

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-03 09:25

    Thanks to @JaredPar and @lpthnc for pointing me in the right direction. I ended up using an approach very similar to what @JaredPar outlines above. Here's my working macro FWIW.

    Imports System.IO
    Imports System.Collections.Generic
    Imports EnvDTE
    
    Public Module Main
    
        Sub IncludeNewFiles()
            Dim Count As Integer = 0
            For Each Project As Project In DTE.Solution.Projects
                If Project.UniqueName.EndsWith(".vbproj") Then
                    Dim NewFiles As List(Of String) = GetFilesNotInProject(Project)
                    For Each File In NewFiles
                        Project.ProjectItems.AddFromFile(File)
                    Next
                    Count += NewFiles.Count
                End If
            Next
            DTE.StatusBar.Text = String.Format("{0} new file{1} included in the project.", Count, If(Count = 1, "", "s"))
        End Sub
    
        Private Function GetAllProjectFiles(ByVal ProjectItems As ProjectItems, ByVal Extension As String) As List(Of String)
            GetAllProjectFiles = New List(Of String)
            For Each ProjectItem As ProjectItem In ProjectItems
                For i As Integer = 1 To ProjectItem.FileCount
                    Dim FileName As String = ProjectItem.FileNames(i)
                    If Path.GetExtension(fileName).ToLower = Extension Then
                        GetAllProjectFiles.Add(fileName)
                    End If
                Next
                GetAllProjectFiles.AddRange(GetAllProjectFiles(ProjectItem.ProjectItems, Extension))
            Next
        End Function
    
        Private Function GetFilesNotInProject(ByVal Project As Project) As List(Of String)
            Dim StartPath As String = Path.GetDirectoryName(Project.FullName)
            Dim ProjectFiles As List(Of String) = GetAllProjectFiles(Project.ProjectItems, ".vb")
            GetFilesNotInProject = New List(Of String)
            For Each file In Directory.GetFiles(StartPath, "*.vb", SearchOption.AllDirectories)
                If Not ProjectFiles.Contains(file) Then GetFilesNotInProject.Add(file)
            Next
        End Function
    
    End Module
    

提交回复
热议问题