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
}");
var region = tree.GetRoot()
.DescendantNodes(descendIntoTrivia: true)
.OfType<RegionDirectiveTriviaSyntax>()
.Single();
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
}
source
share