我知道我可以用裸XML做到这一点,但我很好奇Roslyn是否允许我这样做。
我目前的代码是:
MSBuildLocator.RegisterDefaults();
using (var workspace = MSBuildWorkspace.Create())
{
workspace.LoadMetadataForReferencedProjects = true;
var solution = await workspace.OpenSolutionAsync(solutionFile);
foreach (var project in solution.Projects)
{
foreach (var csFile in project.Documents.Where(o => o.SupportsSyntaxTree && o.Name.EndsWith(".cs")))
{
// Do some per cs file processing
}
// I want to check the imports and if the one I need is missing - add it.
}
}
如何提取有关导入的信息?最好使用FullSpan位置,这样我就可以方便地编辑原始文件。
Roslyn对MSBuild一无所知。 MSBuildWorkspace使用计算机上安装的MSBuild实例来计算将传递给编译器的命令行。如果你想检查项目文件本身,我会看看使用MSBuild apis,特别是ProjectRootElement和 Project