Created
March 23, 2022 03:34
-
-
Save tackme31/ee3e304a0e2f8e6e6d68a162347672cc to your computer and use it in GitHub Desktop.
Remove comments by Roslyn
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.CodeAnalysis; | |
using Microsoft.CodeAnalysis.CSharp; | |
var programBefore = @" | |
public class MyClass | |
{ | |
public void MyMethod() | |
{ | |
// Output | |
Console.WriteLine(""Hello, world!""); | |
} | |
} | |
"; | |
var tree = CSharpSyntaxTree.ParseText(programBefore).GetCompilationUnitRoot(); | |
var commentTrivias = tree.DescendantTrivia().Where(trivia | |
=> trivia.IsKind(SyntaxKind.SingleLineCommentTrivia) | |
|| trivia.IsKind(SyntaxKind.MultiLineCommentTrivia)); | |
var commentsRemoved = tree.ReplaceTrivia(commentTrivias, (_, _) => SyntaxFactory.CarriageReturn); | |
var programAfter = commentsRemoved.ToString(); | |
Console.WriteLine(programAfter); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment