Andrea
Andrea

Reputation: 894

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.

Upvotes: 4

Views: 2005

Answers (2)

Anton Krouglov
Anton Krouglov

Reputation: 3399

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.

Upvotes: 8

EBarr
EBarr

Reputation: 12026

This question seems to answer:

How do you call "Document Format" programmatically from C#?

The short is use Visual Studio's object model to call the format command.

Upvotes: 1

Related Questions