Florida Housing Market

May 30, 2008

Checking Whether a File Is an Assembly

A file is an assembly if and only when if it’s pulled off and it comprises an Assembly entry in its CLR metadata.

Determining by hand

A degraded way to ascertain whether a file is an assembly is to campaign ildasm.exe on it. If it right away consecrates an error supposing that it may not be a PE file, and so it’s not a pulled off file. But, if it is an assembly, so ildasm will usher an entry for the Assembly definition (“.assembly“ in the MANIFEST window or at the bottom of the original window).

Finding out programmatically

From unmanaged code, you can ring GetAssemblyFromScope() on the IMetaDataAssemblyImport interface for the file. If it yields S_OK, it’s an assembly. If it renders CLDB_E_RECORD_NOTFOUND, it’s not an assembly.

From brought off code, if AssemblyName.GetAssemblyName(), Assembly.Load*(), etc. follows when paid that file, and so it’s an assembly. If the load failed with a BadImageFormatException, and then it may not be an assembly. There are other reasons, all the same, why that exception may have been held (peradventure it’s an assembly but could not be charged because it has an wrong format). Making out presently in v2, if the hresult for BadImageFormatException is COR_E_ASSEMBLYEXPECTED, and then it’s because it’s not an assembly. Arrest the exception and phone System.Runtime.InteropServices.Marshal.GetHRForException() to obtain its hresult to rule out.

Observe that this takes up that you are not concerned about performance. If you are concerned about that, so the way to optimize for it is to not try on to ascertain whether files are assemblies at runtime at all. (Some people are concerned about the exception that is fuddled if the file is not an assembly. They overleap that in order to see that it is not one, it has to be charged and and then bedeviled off, which can be even more expensive than geting an exception!) Rather, ask that only assemblies are given to you. And then, if a file is not an assembly, it will be an olympian situation. That way, you head off the big perf of both the exception and the unneeded file loading.

Related Posts:
2,433 Unread Emails, I find your pain..
Language geek at the Maker Faire

Comments

The URI to TrackBack this entry is: http://kerryzan.blogsome.com/2008/05/30/checking-whether-a-file-is-an-assembly/trackback/

No comments yet.

RSS feed for comments on this post.

Leave a comment

Sorry, the comment form is closed at this time.

Get free blog up and running in minutes with Blogsome
Theme designed by Jay of onefinejay.com