Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to persist a solution with projects and documents using Roslyn's AdhocWorkspace?

I've been trying to persist a new solution containing a project and a simple cs file with the following code but nothing get saved to the disk. Am I doing something wrong or is Roslyn not the tool to be used to generate solutions project and files?

class Program
{
    static void Main(string[] args)
    {
        var workspace = new AdhocWorkspace();

        var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(),
                                               VersionStamp.Create(),
                                               @"C:\Seb\SebSol.sln");

        var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(),
                                             VersionStamp.Create(),
                                             "SebProj",
                                             "SebProj.dll",
                                             LanguageNames.CSharp,
                                             @"C:\Seb\SebSol\SebProj\SebProj.csproj");

        workspace.AddSolution(solutionInfo);
        workspace.AddProject(projectInfo);

        var sourceText = SourceText.From("public class A { }");
        workspace.CurrentSolution.AddDocument(DocumentId.CreateNewId(projectInfo.Id), "ClassA.cs", sourceText);

        workspace.TryApplyChanges(workspace.CurrentSolution);
    }
}
like image 795
Sebastiano1972 Avatar asked Dec 04 '25 17:12

Sebastiano1972


1 Answers

You're looking for MsBuildWorkspace, which can actually update sln and csproj files in MSBuild format on disk.

Other than that class, Roslyn APIs are completely agnostic to project formats such as MSBuild.

like image 179
SLaks Avatar answered Dec 06 '25 07:12

SLaks