ProjectItems.AddFromDirectory不适用于VS2015

时间:2015-08-07 08:57:07

标签: c#

我需要以编程方式将目录复制到我的项目中。我在我的项目中使用了以下代码:

ProjectItems.AddFromDirectory(_projectPath + "\\Folder");

但它不会复制整个目录。它只是将根文件夹添加到项目中。我单独面对VS2015。

对此有何解决方案?

1 个答案:

答案 0 :(得分:0)

This might not be the most elegant solution possible. But it is using AddFromDirectory as requested. I tested this using Visual Studio 2015 Professional.

public static void RefreshItemsInProject(Project project, string projectPath)
{
  foreach(string subDirectoryPath in Directory.EnumerateDirectories(projectPath))
    AddItemsToProjectFromDirectory(project.ProjectItems, subDirectoryPath));
}

private static readonly HashSet<string> _excluded = new HashSet<string>() { "bin", "obj" };

public static void AddItemsToProjectFromDirectory(ProjectItems projectItems, string directoryPath)
{
  //very weird GetDirectoryName returns the FULL PATH!!!! 
  //When using GetFileName on a Directory it actually returns the FolderName WITHOUT the PATH.
  var directoryName = Path.GetFileName(directoryPath);

  if(_excluded.Contains(directoryName.ToLower()))//folder to exclude like bin and obj.
    return;//return right away if the folder has been excluded.

  var subFolder = projectItems.AddFromDirectory(directoryPath);

  foreach(string subDirectoryPath in Directory.EnumerateDirectories(directoryPath))
    AddItemsToProjectFromDirectory(subFolder.ProjectItems, subDirectoryPath);
}

To use this code call like this:

RefreshItemsInProject(myProject, projectPath);

myProject is of type EnvDTE.Project

You can call this on a project everytime something changes; like a new file was added for example; and it will refresh the contents of the project.

Notice it supports a list of "excluded" Directories to avoid including things like bin and obj in your project.

I hope this helps some one.

UPDATE: I realized this only works for SECOND LEVEL directories. Like this:

MyDir--->MySecondDir--->MyItems THIS WORKS! Items in second level.

MyDir--->MyItems THIS DOES NOT WORK! Items in first level.

For some reason it fails to add the items in the first level directory. Seems like a bug in Microsofts implementation. If some one could shed some light into the issue; I would really appreaciate it.