如何从 C# 中识别 .exe 文件是 32 位还是 64 位

问题描述 投票:0回答:1

如何确定 C# 中的 .EXE 文件(不是我的应用程序、不是另一个正在运行的应用程序、不是 .NET 应用程序)是 32 位还是 64 位?我发现的最好的就是这个,我猜有一个本机 .NET 调用。

.net 32bit-64bit portable-executable
1个回答
0
投票

如果您不使用第三方库或winAPI,这里有一个读取标头并获取信息的方法。

enum PlatformFile : uint
        {
            Unknown = 0,
            x86 = 1,
            x64 = 2
        }
        static PlatformFile GetPlatformFile(string filePath)
        {
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            using (BinaryReader br = new BinaryReader(fs))
            {
                fs.Seek(0x3C, SeekOrigin.Begin);
                int peOffset = br.ReadInt32();
                fs.Seek(peOffset, SeekOrigin.Begin);
                uint peHead = br.ReadUInt32();

                if (peHead != 0x00004550)
                    return PlatformFile.Unknown;

                fs.Seek(peOffset + 4, SeekOrigin.Begin);
                ushort machine = br.ReadUInt16();

                if (machine == 0x014c) // IMAGE_FILE_MACHINE_I386
                    return PlatformFile.x86;
                else if (machine == 0x8664) // IMAGE_FILE_MACHINE_IA64 or IMAGE_FILE_MACHINE_AMD64
                    return PlatformFile.x64;
                else
                    return PlatformFile.Unknown;
            }
        }
© www.soinside.com 2019 - 2024. All rights reserved.