I want to programmatically add an Import to an MSBuild project. The API in this Microsoft.Build.Evaluation namespace allows me to to this (I'd prefer to achieve the same result through the VS extensibility API but there doesn't seem to be any way to do that so I'm resorting to this API).
If I want to open one or more Projects in a method, look at their Imports, and sometimes add an import, how am I supposed to use ProjectCollection object? Do I always create a new ProjectCollection, load projects into it, then unload them all at the end of the method?
我有可以做我想要的工作代码,我只是无法猜测如何“正确”使用这个 API,因为只提供了通常的低级参考文档。
好吧,在我找不到任何关于如何使用这个 API 的建议的情况下,我最终在任何时候想使用项目对象时创建一个新的 ProjectCollection,然后在 ProjectCollection 上调用 UnloadAllProjects。
/// <summary>
/// Do something with a Microsoft.Build.Evaluation.Project.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="projectPath"></param>
/// <param name="worker"></param>
/// <returns></returns>
static T WithProject<T>(string projectPath, Func<Project, T> worker)
{
var pc = new ProjectCollection();
try
{
if (string.IsNullOrWhiteSpace(projectPath))
return default(T);
var evalProject = pc.LoadProject(projectPath);
return worker(evalProject);
}
catch
{
return default(T);
}
finally
{
pc.UnloadAllProjects();
}
}
Run Code Online (Sandbox Code Playgroud)
或者,更简单(从使用 ILSpy 窥探别人的 DLL):
public static Project GetMSBuildProject(string projectPath)
{
Project project = null;
if (project == null)
{
project = new Project(projectPath, new Dictionary<string, string>(), "12.0", new ProjectCollection());
}
return project;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1904 次 |
| 最近记录: |