Paste code between regions with Roslyn

How can I insert a variable declaration after the region directive in Roslyn? I would like to do something like this:

class MyClass 
{
    #region myRegion
    #endregion
}

:

class MyClass 
{
    #region myRegion
    private const string myData = "somedata";
    #endregion 
}

It seems that I can not find examples that relate to details in this way.

+1
source share
1 answer

This is quite difficult to do with CSharpSyntaxRewriter , because both the tags #region <name>and the ones #endregionare the same SyntaxTriviaList, which you will have to split and figure out what to create instead. The easiest way to not worry about all the intricacies is to create one TextChangeand change it SourceText.

var tree = SyntaxFactory.ParseSyntaxTree(
@"class MyClass
{
    #region myRegion
    #endregion
}");

// get the region trivia
var region = tree.GetRoot()
    .DescendantNodes(descendIntoTrivia: true)
    .OfType<RegionDirectiveTriviaSyntax>()
    .Single();

// modify the source text
tree = tree.WithChangedText(
    tree.GetText().WithChanges(
        new TextChange(
            region.GetLocation().SourceSpan,
            region.ToFullString() + "private const string myData = \"somedata\";")));

After that tree:

class MyClass 
{
    #region myRegion
private const string myData = "somedata";
    #endregion
}
+3
source

All Articles