将项目对象写入项目文件

本文关键字:项目文件 对象 项目 | 更新日期: 2023-09-27 18:27:42

我正在使用Roslyn进行一些代码转换,程序的选项之一是输出转换后的源文件。不过,我想把这个项目和*.csproj文件放在一起。我用来整理文件的代码是

 foreach (var project in solution.Projects)
        {
            foreach (var doc in project.Documents)
            {
                var fileName = Path.GetFileName(doc.FilePath);
                var directory = Path.Combine(Path.GetDirectoryName(doc.FilePath), "output");
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                var outputPath = Path.Combine(directory, fileName);
                using (var writer = new System.IO.StreamWriter(File.OpenWrite(outputPath)))
                {
                    doc.GetText().Write(writer);
                }
            }
        }

我也想插入几行来输出项目,与文件

将项目对象写入项目文件

位于同一目录中

通常,您可以使用Workspace.ApplyChanges()方法将对文档和项目的更改输出到它们的原始位置。请注意,ApplyChanges并不支持所有可能的项目更改。

通常,对于足够复杂的项目文件更改,您应该直接使用MSBuild API来操作.csproj文件。