Tutorial :C# to format (indent, align) C# properly

Question:

We have a code generator that munges the schema of a given database to automate our inhouse n-tier architecture. The output is various C# partial classes, one per file.

In the code to munge all the strings, we try and keep on top of the indenting and formatting as much as possible, but invariably when you come to open the file in Visual Studio the formatting is awry. A quick ctrl-k, ctrl-d fixes it, but obviously this reformatting is lost the next time the class is generated.

What I'd like to know, is if there's a way I can somehow automatically format the contents of the textfile in the same way Visual Studio does?

EDIT: I should clarify - I want to be able to invoke the formatting from my C# code that creates the textfile containing my generated C#. The format of the code can be standardised (doesn't have to be per-developer), and I don't want to have to install any 3rd-party apps.

FURTHER EDIT: My code generator is a winforms app deployed via a click-once install. It's used by many developers in-house. I need a solution that doesn't require each developer to have a tool installed on their machine.

Solution:1

To Expand on Cherian's answer:

NArrange will allow you to do a lot of code formatting. It is open source, and the source is available on their site, so you could potentially integrate and redistbute it with your tool.

You should only need the dll's and just look at the exe on how to call the formatting. It will also create a backup of the code being formatted. It is really a nice tool if it fits your needs.

Solution:2

Take a look at Narrange.You'll probably need to automate these things as part of the build. Not sure if it meets all your requirements though.To quote:

NArrange is a .NET code beautifier that automatically organizes code members and elements within .NET classes.

Solution:3

You can use CodeDOM and the CSharpCodeProvider. It is all in the namespaces Microsoft.CSharp and System.CodeDom.