我想编写一个宏以在项目目录中的文件中进行爬网,并找到项目中未包含的文件。
在玩DTE对象时,我看到Project
对象具有ProjectItems
;如果ProjectItem
表示目录,则它具有自己的ProjectItems
集合。这给了我项目中包含的所有文件。
因此,我可以递归地浏览每个ProjectItems集合,并为作为目录的每个ProjectItem,检查文件系统中是否存在没有相应ProjectItem的文件。不过,这似乎很笨拙。
有更简单的方法来解决这个问题的想法吗?
最佳答案
这是您的代码的C#版本:
public static void IncludeNewFiles()
{
int count = 0;
EnvDTE80.DTE2 dte2;
List<string> 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<string> GetAllProjectFiles(ProjectItems projectItems, string extension)
{
List<string> returnValue = new List<string>();
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<string> GetFilesNotInProject(Project project)
{
List<string> returnValue = new List<string>();
string startPath = Path.GetDirectoryName(project.FullName);
List<string> projectFiles = GetAllProjectFiles(project.ProjectItems, ".cs");
foreach (var file in Directory.GetFiles(startPath, "*.cs", SearchOption.AllDirectories))
if (!projectFiles.Contains(file)) returnValue.Add(file);
return returnValue;
}
关于visual-studio - Visual Studio宏: Find files that aren't included in the project?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2000197/