9

I'm trying to parse a simple.cs source file using the following code:

CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
var compileUnit = provider.Parse(File.OpenText(filename));

This gives me a NotImplementedException:

"This CodeDomProvider does not support this method"

Is it true that .NET does not provide an implemenation for parsing C# code? Or am I just using this class the wrong way?

Edit: The reason for doing this is that I want to toy around with some methods for static code analysis. Compiling or executing the code is not required for my research.

7
  • 3
    I'd suggest you look into using Roslyn instead of CodeDomProvider for this. Commented Sep 29, 2014 at 5:54
  • 1
    stackoverflow.com/questions/7852926/microsoft-roslyn-vs-codedom Commented Sep 29, 2014 at 6:23
  • @JonSkeet any particular reasons why you would suggest that? Commented Sep 29, 2014 at 7:01
  • 1
    @Mick: Well it's a rather more modern representation which the C# team has been working on for several years - and which can definitely parse C#. Commented Sep 29, 2014 at 7:16
  • 1
    @Mick: While you may be able to, the question doesn't make it sound promising - and I don't know what the future of CSharpCodeProvider is in terms of C# 6 etc. I know the team has said that C# 6 will not be implemented in the native compiler. The Roslyn representation is likely to be considerably richer than what CSharpCodeProvider gives, too. Commented Sep 30, 2014 at 5:49

1 Answer 1

10

Yes, that's true, the CodeDomProvider is for emitting source code, not reading it. Various companies have their own parsers and recently Microsoft started project Roslyn that provides such features.

Sign up to request clarification or add additional context in comments.

4 Comments

Your answer isn't correct, you can "read" source code and compile it with CodeDom... I think Roslyn, whilst very cool, it might be overkill for what he needs.
@Mick By "read", I meant you cannot generate a parsed syntax tree from code. You may be able to compile code, but you cannot access the Parse step of the compilation process alone. It's obviously in there somewhere but inaccessible to the user.
I think you're making assumptions about what he's trying to achieve, most people just want to spit out an assembly and execute it CSharpCodeProvider is pretty good at doing that and is simple to use.
I really want to get the syntax tree, not compile anything. So Microsoft keeps this part of their implementations locked away? I guess I'll have to wait for Roslyn then. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.