Hi,
I'm trying to add files to projects organizing them in folders before adding. The scenarios:
1. Before adding the file check if the folder exists as a project item. If so, the project item is used to add the file.
2. Otherwise check if the folder path exists. If so, include folder path as project item and use to add the file.
3. Otherwise the folder is unknown. Add the folder as project item and use to add the file.
Scenario 1 and 3 work, but I can't get scenario 2 to work. The code:
var service = package.GetService<SDTE, EnvDTE80.DTE2>(); foreach (Project project in service.Solution.Projects) { var folder = project.AddFolderIfNotExists("Folder"); var file = folder.ProjectItems.AddFromFileCopy(@"c:\temp\somefile.cs"); }
public static class ProjectItemsExtensions
{
public static Guid ProjectItemKindFolder = new Guid("{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}");public static ProjectItem GetFolder(this Project project, string folderName)
{
ThreadHelper.ThrowIfNotOnUIThread();
foreach (ProjectItem item in project.ProjectItems)
{
var kind = new Guid(item.Kind);
if (kind != ProjectItemKindFolder) continue;
if (item.Name.ToLowerInvariant().Equals(folderName.ToLowerInvariant())) return item;
}
return null;
}public static ProjectItem AddFolderIfNotExists(this Project project, string folderName)
{
//*****
ThreadHelper.ThrowIfNotOnUIThread();//***** Determine if folder is included in the project;
var folder = GetFolder(project, folderName);
if (folder != null) return folder;//***** Determine if the folder path exists. If so include in the project;
var projectPath = Path.GetDirectoryName(project.FileName);
var folderPath = Path.Combine(projectPath, folderName);
if (Directory.Exists(folderPath)) return project.ProjectItems.AddFolder(folderPath);//***** Else add folder;
folder = project.ProjectItems.AddFolder(folderName);
return folder;
}
}
The AddFolder methods throws an exception that the folder already exists.
When adding the file I need the folder first as project item to add it in context. No luck with the AddFile* methods as well.
Any ideas on how I can include the folder in the project?
Cheers,
Peter