Okay...
I have some CSharp code that can dynamically compile a statement:
***
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters param = new CompilerParameters(null, "w00t.exe", true);
param.GenerateExecutable = true;
ICodeCompiler cc = provider.CreateCompiler();
CompilerResults cr = cc.CompileAssemblyFromSource(param, source);
***
Where source is a sourcecode string. Now, that is great but there is a
problem. I don't really want to compile the code, I just want to
evaluate if the syntax is correct. This particular piece of code
expects and entire namespace, class, etc to be present. In my case, I
just want to check if a small snippet of code is correct.
For example this string:
"FileStream fs = new FileStream(\"C:/newFile.txt\",
\nFileMode.Create);\nByte[] bytes = new Byte[2];\nbytes[0] =
65;\nbytes[1] = 66;\nfs.Write(bytes, 0, 2);\nfs.Close();";
Will fail to compile with the error:
error CS0116: A namespace does not directly contain members such as
fields or methods
I would like to know a way, to programatically evaluate the string
above for syntactic correctness without having to add Methods, or
namespaces to the code. The reason I don't want to do this, is because
there will be times when the code string I pass to this function may
contain a namespace, and I generally want to avoid having to write
code to detect this.
Thanks in advance. |