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

后端 未结 4 1964
情深已故
情深已故 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:39

    Here is the C# version of your code:

    public static void IncludeNewFiles()
    {
        int count = 0;
        EnvDTE80.DTE2 dte2;
        List newfiles;
    
        dte2 = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.10.0");
    
        foreach (Project project in dte2.Solution.Projects)
        {
            if (project.UniqueName.EndsWith(".csproj"))
            {
                newfiles = GetFilesNotInProject(project);
    
                foreach (var file in newfiles)
                    project.ProjectItems.AddFromFile(file);
    
                count += newfiles.Count;
            }
        }
        dte2.StatusBar.Text = String.Format("{0} new file{1} included in the project.", count, (count == 1 ? "" : "s"));
    }
    
    public static List GetAllProjectFiles(ProjectItems projectItems, string extension)
    {
        List returnValue = new List();
    
        foreach(ProjectItem projectItem in projectItems)
        {
            for (short i = 1; i <= projectItems.Count; i++)
            {
                string fileName = projectItem.FileNames[i];
                if (Path.GetExtension(fileName).ToLower() == extension)
                    returnValue.Add(fileName);
            }
            returnValue.AddRange(GetAllProjectFiles(projectItem.ProjectItems, extension));        
        }
    
        return returnValue;
    }
    
    public static List GetFilesNotInProject(Project project)
    {
        List returnValue = new List();
        string startPath = Path.GetDirectoryName(project.FullName);
        List projectFiles = GetAllProjectFiles(project.ProjectItems, ".cs");
    
        foreach (var file in Directory.GetFiles(startPath, "*.cs", SearchOption.AllDirectories))
            if (!projectFiles.Contains(file)) returnValue.Add(file);
    
        return returnValue;
    }
    

提交回复
热议问题