Visual Studio 扩展重新加载项目

Visual Studio Extension Reload Project

我创建了一个简单的 visual studio 2015 扩展,为当前项目添加了 class。

Project p = (Project) ProjectsComboBox.SelectedItem;

string projectLocation = Path.GetDirectoryName(p.FileName);
// I load the project where I want to Add file
var projectCurrent = new Microsoft.Build.Evaluation.Project(p.FileName);


string relativeNewPath = "\Model\DAL\" + ViewNameTexBox.Text + "DAO.cs";
string newPath = projectLocation + relativeNewPath;

projectCurrent.AddItem("Compile", relativeNewPath);
projectCurrent.Save();

// Once class added to my project I edit text inside newly create class
string text = File.ReadAllText("Templates/DAO.cs.txt");
text = text.Replace("$viewName$", ViewNameTexBox.Text);
File.WriteAllText(newPath, text);

文件包含在项目中并已修改,但visual studio提示一条消息要求重新加载项目。当我这样做时,项目不会重新加载。

the project has been modified outside the environment

我想处置 currentProject,但项目不是 IDisposable。将 currentProject 设置为 null 无效。

如何让我的代码释放 currentProject 并让 Visual Studio 重新加载它?

您可以在添加文件到项目之前卸载项目,然后重新加载项目,以下代码供您参考。

Microsoft.Build.Evaluation.ProjectCollection projectCollection = new Microsoft.Build.Evaluation.ProjectCollection();

var projectCurrent = projectCollection.LoadProject(projectPath);
projectCollection.UnloadProject(projectCurrent);

string relativeNewPath = "\Model\DAL\DAO.cs";
string newPath = projectPath + relativeNewPath;
projectCurrent.AddItem("Compile", relativeNewPath);
projectCurrent.Save();
projectCollection.LoadProject(projectPath);