C# reflection and auditing types
I'm trying to figure out if it's possible via reflection (or otherwise) to "audit" some code to enforce validation requirements -- such as checking whether or not code creates any threads (System.Threadi开发者_如何学编程ng.Thread) or uses other BCLs. The assumption is that the code is already compiled into a dll. Thanks!
Look at FxCop. It can load a compiled binary (dll or exe) and perform validation and compliance checking against that compiled IL, regardless of the .NET language used to write it.
You can write your own rules - which you would do in this case to catch cases of "= new Thread()" and the like.
You can do this with reflection if you are very well-versed in IL.
MethodBody mb = this.GetType().GetMethod( "Method", BindingFlags.Default ).GetMethodBody();
byte[] bytes = mb.GetILAsByteArray();
Probably way more trouble than it is worth; the resulting IL will need to be parsed.
An IL parser (but somewhat dated): http://www.codeproject.com/KB/cs/sdilreader.aspx which will generate a list of OpCodes for you (look for OpCodes.Newobj for instantiation of a Thread).
As others have said reflection won't help you as it only describes the metadata of tpyes.
However, the Mono.Cecil project is a runtime way of actually looking at the IL (Intermediate Language) of types within an assembly. Although a product of the Mono framework it is compatible with the Microsoft CLR.
Reflection does not allow inspection of the body of members, only their signatures. In other words, it won't tell you anything about what a particular method or property does, just what it looks like.
To do what you're after, you'll have to use something like ildasm.exe
to turn the compiled .dll or .exe into IL, then go over the IL and see if it's doing anything to which you object.
Reflection will allow you to inspect the body of methods through MethodBase.GetMethodBody, which gives you a MethodBody to inspect.
However, at this level you are dealing with raw IL in a byte array, which you have to analyze start to end to find out calls to external methods and what they do etc.
So it won't be pretty or easy, but certainly it's possible.
精彩评论