vNext
vNext

Reputation: 1122

Add files and folder to projects from Addin in Visual Studio 2010

Add files and folder to projects from Addin in Visual Studio 2010

I can add a file to root folder of project using:

ActiveProject.ProjectItems.AddFromFileCopy(tempPath);

Or add a folder using:

ActiveProject.ProjectItems.AddFromDirectory(path);

But how can I add a file to an existing folder in projects? If I use ActiveProject.ProjectItems.AddFromDirectory(path); This will be an error "folder is existing".

Upvotes: 2

Views: 310

Answers (1)

Ursegor
Ursegor

Reputation: 878

It is sketchy a bit but you can do easily by this on your own:

Usage:

    string relFilePath = @"MyFolder\output.txt"; // Relative to project root

    string filePath = @"C:\output.txt"; // Place of the file

    activeProject.ProjectItems.AddExistingFile(relFilePath, filePath);

An extension method for ProjectItems:

static class ProjectItemExtender
{
    const string folderKindGUID = "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}";

    public static ProjectItem AddExistingFile( this ProjectItems projectItemCollection, string relPath, string filePath )
    {
      string[] path = relPath.Split('\\');

      if (path.Length == 0) return null;

      Func<ProjectItem, bool> folderPredicate = (item) => 
          (item.Kind == folderKindGUID && path.FirstOrDefault() == item.Name);

      ProjectItem actItem = projectItemCollection.Cast<ProjectItem>().FirstOrDefault(folderPredicate);

      //Create not existing folders on path
      if (actItem == null && path.Length > 1)
      {
        //Could throw an exception on invalid folder name for example...
        projectItemCollection.AddFolder(path[0]);

        actItem = projectItemCollection.Cast<ProjectItem>().FirstOrDefault(folderPredicate);
      }
      else if (path.Length == 1)
      {
        projectItemCollection.AddFromDirectory(filePath);
      }

      return path.Length == 1 ?
                                  actItem
                              :
                                  actItem.ProjectItems.AddExistingFile(path.Skip(1).Aggregate((working, next) => working + "\\" + next), filePath);
    }
}

All you need to do is to add the file through the folder and not the project.

Upvotes: 1

Related Questions