Blog Stats
  • Posts - 99
  • Articles - 5
  • Comments - 236
  • Trackbacks - 105

 

Random Useful Code

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();

      }

}

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Feedback

# re: Random Useful Code

Gravatar Useless Trivia: What does the "MZ" header value mean?

Mark Zbikowski's initials. He designed the MSDOS executable file format. 5/9/2006 5:43 PM | Keith Rome

# re: Random Useful Code

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
5/10/2006 1:16 PM | Alois Kraus

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

 

 

Copyright © Greg Young