Geeks With Blogs
Greg Young Greg.ToString()

I don't remember where I got this (so whoever you are thanks but I can't link to you update .. http://groups.google.de/group/microsoft.public.de.german.entwickler.dotnet.framework/msg/1af0719168e45e84) some time ago but it is a quite useful (and portable) way to see if a file is a .NET assembly or not ... If you fall back to the Assembly.LoadFrom method .. you have to fail many times if you are searching many files ... In looking at this again (had nearly forgotten about it until today). It works by checking the PE/COFF http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx header of the file.

I told myself that I would clean it up a bit, make less exceptions happen if files were not big enough etc .. guess I have to put that on my board. 

static bool IsClrImage( string fileName ) {

      FileStream fs = null;

      try {

            fs = new FileStream( fileName, FileMode.Open, FileAccess.Read,

                  FileShare.Read );

            byte[] dat = new byte[300];

            fs.Read( dat, 0, 128 );

            if( (dat[0] != 0x4d) || (dat[1] != 0x5a) ) // "MZ" DOS header

                  return false;

 

            int lfanew = BitConverter.ToInt32( dat, 0x3c );

            fs.Seek( lfanew, SeekOrigin.Begin );

            fs.Read( dat, 0, 24 ); // read signature & PE file header

            if( (dat[0] != 0x50) || (dat[1] != 0x45) ) // "PE" signature

                  return false;

 

            fs.Read( dat, 0, 96 + 128 ); // read PE optional header

            if( (dat[0] != 0x0b) || (dat[1] != 0x01) ) // magic

                  return false;

 

            int clihd = BitConverter.ToInt32( dat, 208 ); // get IMAGE_COR20_HEADER

            rva-address

                  return clihd != 0;

      }

      catch( Exception ) {

            return false;

      }

      finally {

            if( fs != null )

                  fs.Close();

      }

}

Posted on Tuesday, May 9, 2006 4:01 PM Tips and Tricks , Under the covers | Back to top


Comments on this post: Random Useful Code

# re: Random Useful Code
Requesting Gravatar...
Useless Trivia: What does the "MZ" header value mean?

Mark Zbikowski's initials. He designed the MSDOS executable file format.
Left by Keith Rome on May 09, 2006 5:43 PM

# re: Random Useful Code
Requesting Gravatar...
Hi Greg,

when you extend this code a little bit you can also tell for what target CPU (Any, x32, x64) it was compiled and if it is managed you can do Assembly.ReflectionOnlyLoad and find out if it was compiled in Debug or Release mode.

Yours,
Alois Kraus
Left by Alois Kraus on May 10, 2006 1:16 PM

Your comment:
 (will show your gravatar)


Copyright © Greg Young | Powered by: GeeksWithBlogs.net