Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

API for indentation of generated C#

In my current project, we have a couple of code generator routines to help us through some mindless tasks. Everything works fine from the technical point of view, so that might be more a curiosity than a real issue: when I open a newly generated piece of code, it is (of course) not properly indented (although syntactically correct).

Now, the question: is there an API somewhere that can be used to indent a piece of C# code? Much like what happens when I use the shortcut Ctrl+E,D in VS2010.

Just to clarify, I am looking for a function like that:

string GetProperlyFormattedCode(string notFormattedCode);

where notFormattedCode is a piece of valid c# source code, and the output of the function is the same code after application of formatting rules. In other words, I am looking for the function that lies behind the "Edit -> Advanced -> Format selection" command of Visual Studio.

like image 932
Andrea Avatar asked Oct 16 '25 13:10

Andrea


1 Answers

To indent code just use Microsoft.CodeAnalysis.CSharp nuget package and .NET framework 4.6+. Sample code:

public string ArrangeUsingRoslyn(string csCode) {
    var tree = CSharpSyntaxTree.ParseText(csCode);
    var root = tree.GetRoot().NormalizeWhitespace();
    var ret = root.ToFullString();
    return ret;
}

One-liner:

csCode = CSharpSyntaxTree.ParseText(csCode).GetRoot().NormalizeWhitespace().ToFullString();

You may also use NArrange to sort methods in your cs file, organize usings, create regions, etc. Note that NArrange does not indent anything.

like image 152
Anton Krouglov Avatar answered Oct 19 '25 04:10

Anton Krouglov