在 Roslyn 项目中创建新文件夹

Creating a New Folder in a Roslyn Project

我有一个 Project 参考,我正在通过 AddDocument() 向该项目添加一个新的 Document。问题是,无论我在调用中发送什么,新文件总是在项目的根目录中结束。我试过在文件的 name 前加上一个子目录:

project.AddDocument(@"\GoHere\MyNewFile.cs", ...)

但这不起作用。这也不是:

project.AddDocument(@"\GoHere\MyNewFile.cs", ..., filePath: @"C:\ProjectPath\GoHere");

我也尝试了其他选项,但均无济于事。编译器 API 中是否有某种方法可以将文件添加到不存在的新子目录中的项目?如果是这样,如何? TIA.

获取项目的根文件夹并在添加文件之前自行创建目录。使用 Directory.Create()Path.Combine() 来实现这一点。

我认为您只需要在 AddDocument

上使用可选参数 folders
SourceText text; 
List<string> folders = new List<string>() { "GoHere" };
project.AddDocument(@"MyNewFile.cs", text, folders: folders);

因为你提到了 VS,我只是从 VSPackage 的 Initialize() 仔细检查了这个。

var componentModel = (IComponentModel)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(SComponentModel));
var workspace = componentModel.GetService<VisualStudioWorkspace>();

var sourceText = SourceText.From("Test");
var folders = new List<string>() { "GoHere" };
var proj = workspace.CurrentSolution.Projects.Single();
var document = proj.AddDocument("Test.cs", sourceText, folders);

var result = workspace.TryApplyChanges(document.Project.Solution);

似乎正确添加了文档: