NRefactory 5 starting with a simple example

I would like to start using NRefactory 5 to parse CSharp files to do refactoring. But the documentation is not enough. So I tried and failed: I started with the following code to find out if I can get the AstNode tree from the cs file.

I would expect that parsing works out for me some nodes, but no. Can anybody help me?

 TextReader reader = File.OpenText(fname); CompilationUnit compilationUnit; CSharpParser parser = new CSharpParser(); compilationUnit = parser.Parse(reader, fname); AstNode node = compilationUnit.GetNextNode(); System.Collections.Generic.IEnumerable<AstNode> desc = compilationUnit.Descendants; foreach (AstNode jo in desc) { System.Console.WriteLine("At least something here"); } 
+4
source share
2 answers

Take a look at the ICSharpCode.NRefactory.Demo project in the ICSharpCode.NRefactory.Demo source code - it can parse some code and display the syntax tree in TreeView.

The code you entered really needs to create some nodes - compilationUnit.Children will contain direct children (usually these are declarations and a namespace declaration).

As well as the CodeProject article .

+2
source

The compilation unit is now deprecated. It is replaced by a syntax tree.

Try the following code:

  TextReader reader = File.OpenText("myfile.cs"); SyntaxTree syntaxTree; CSharpParser parser = new CSharpParser(); syntaxTree = parser.Parse(reader, "myfile.cs"); IEnumerable<AstNode> desc = syntaxTree.Descendants; foreach(AstNode astNode in desc) { System.Console.WriteLine(astNode.GetType()); } 
0
source

All Articles