Friday, April 13, 2007

Check whether executable is managed

So, another interesting question: "How to check whether the executable file managed or not by code". Answering - ask framework about it version.

        [DllImport("mscoree.dll")]
        private static extern int GetFileVersion(
                        [MarshalAs(UnmanagedType.LPWStr)] string szFilename,
                        [MarshalAs(UnmanagedType.LPWStr)] StringBuilder szBuffer,
                        int cchBuffer,
                        out int dwLength);

But any, even very unmanaged file has file version - you ask. Any managed file has managed signature, so if the file is not managed, the method return COR_E_ASSEMBLYEXPECTED, else it return main core framework version.


 



        private string GetRuntimeVersion(string filename)
        {
            const int CCH = 0x400;
            StringBuilder sb = new StringBuilder(CCH);
            int len;
            int hr = GetFileVersion(filename, sb, sb.Capacity, out len);
 
            if (hr == unchecked((int)0x8007000B))
                return string.Empty; 
            else if (hr < 0)
                throw new Win32Exception(hr);
            else
                return sb.ToString(0, len - 1);
        }

Pretty simple, isn't is?


Source code for this article

No comments: