4

I would like to start using NRefactory 5 for parsing CSharp files, to do refactoring. But the documentation is scarce. So I tried and failed: I started with the following code to see if I could get a AstNode tree from a cs file.

I would expect the parsing to generates some nodes for me, but no. Can somebody guide 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");
}
nemesv
  • 138,284
  • 16
  • 416
  • 359
Ravi
  • 61
  • 1
  • 7

2 Answers2

2

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

The code you posted should indeed produce some nodes - compilationUnit.Children will contain the direct children (usually usings and the namespace declaration).

And there's also the CodeProject article.

Daniel
  • 15,944
  • 2
  • 54
  • 60
  • Thank you for you answer. I also found that using the source code of NRefactory with both demo and tests are the best source. Especially since the new version 5.0 makes most of the examples posted on internet out of date. – Ravi Jun 17 '12 at 06:39
0

Compilation Unit is obsolete now. It is replaced with Syntax Tree.

Try 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());
        }
Utsav Chokshi
  • 1,357
  • 1
  • 13
  • 35