How to tell if a file is an EXE or a DLL?

user541686 picture user541686 · Jun 10, 2011 · Viewed 10.8k times · Source

If you've gotten the file extensions messed up, how can you tell an executable apart from a DLL?

They both seem to have entry points and everything...

Answer

crypted picture crypted · Jun 10, 2011

if anyone interested here is the code in C#, tested for 32 bit PE files.

 public static class PECheck
    {

        public static bool IsDll(Stream stream)
        {

            using (BinaryReader reader = new BinaryReader(stream))
            {

                byte[] header = reader.ReadBytes(2); //Read MZ
                if (header[0] != (byte)'M' && header[1] != (byte)'Z')
                    throw new Exception("Invalid PE file");

                stream.Seek(64 - 4, SeekOrigin.Begin);//read elf_new this is the offset where the IMAGE_NT_HEADER begins
                int offset = reader.ReadInt32();
                stream.Seek(offset, SeekOrigin.Begin);
                header = reader.ReadBytes(2);
                if (header[0] != (byte)'P' && header[1] != (byte)'E')
                    throw new Exception("Invalid PE file");

                stream.Seek(20, SeekOrigin.Current); //point to last word of IMAGE_FILE_HEADER
                short readInt16 = reader.ReadInt16();
                return (readInt16 & 0x2000) == 0x2000;

            }
        }
    }