I'm searching for a function (perhaps there is one in the .Net-Framework) which I can use to validate C#-syntax. It can also be a c# parser with build-in validation.
Background: I'm building a little Code-开发者_开发知识库Generator where the user can enter some definitions and gets back full implemented properties etc., but I want to check if the user entered correct C# and if the result is correct, too.
Edit:
I don't want to compile the code, and it could be uncomplete code. So that for example the User could enter a code-snippet with classes from his code, I don't know, and I only want to validate the syntax, not the 'content'
Examples
Input:
Car car = new Car();
car.drive("50");
Output:
Same as input, because it's valid and nothing to do.
Input:
Car car = new Car()
car.drive("50");
Output:
Message that it is not valid, beause of missing ';'
etc.
I don't know the class Car
and therefore I can't compile it, I only want to check the syntax.
How to programatically compile code using the C# compiler:
http://support.microsoft.com/kb/304655
..it validates as a part of the compilation process. You can get the list of errors like this (from the article..surprising since it's a bit messy):
foreach(CompilerError CompErr in results.Errors)
{
textBox2.Text = textBox2.Text +
"Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
Have a look at this .Net class, http://msdn.microsoft.com/en-us/library/system.codedom.compiler.codedomprovider.aspx
Basically you can call the compiler on the code your looking at and receive back any error messages generated.
Edit: If the code may not compile thats OK, you can look at the error messages returned and ignore stuff like the 'not defined' errors.
You're only other option I think it to write a RegEx that matches the C# language spec.
You'll have to cookup some compilable C# code (using CodeDom or just adding manual snippets around what your users will manually code), and then compile it, as described here: How to programmatically compile code using C# compiler
精彩评论