Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically parse and modify C# code

Tags:

c#

.net

codedom

What I want to do is to read C# code, parse it, insert some method calls and compile it finally.

Is it possible to convert C# source code (a list of strings) to CodeDOM objects?

like image 964
ulrichb Avatar asked Oct 03 '09 16:10

ulrichb


3 Answers

This is a really old question, but is worth noting that the accepted answer no longer applies. Microsoft's recent Roslyn project is explicitly aimed at exposing all the knowledge the compiler gains about your codebase in the process of statically analyzing it, and exposing all this information through managed APIs for you to leverage. It is available for both VB and C#.

Since you want to consume static analysis information, you'll need the Microsoft.CodeAnalysis NuGet package (the stuff you need for C# is under the Microsoft.CodeAnalysis.CSharp namespace) and some time at the samples and walkthroughs page in the docs.

like image 66
Asad Saeeduddin Avatar answered Oct 25 '22 05:10

Asad Saeeduddin


It is not directly possible to do this with the core .NET Framework. You need to use third party or add-on tools, for example:

  • Open source C# Parser: http://www.codeplex.com/csparser
  • GPLEX paired with a C# grammar: http://plas.fit.qut.edu.au/gplex/
like image 26
bobbymcr Avatar answered Oct 25 '22 04:10

bobbymcr


Try Linq over C#. It's wonderful.

like image 38
Tamás Szelei Avatar answered Oct 25 '22 06:10

Tamás Szelei