为什么读取 EXE 作为文本在打印时显示 'MZ'

Why reading EXE as text is showing 'MZ' when printed

String inputFile = "C:\Users\Neil\Desktop\DCR\file.exe";
Byte[] bytes = File.ReadAllBytes(inputFile);
String content = Encoding.Default.GetString(bytes);
Console.WriteLine(content);

的输出

MZ?

当我尝试对另一个文件执行此操作时,我得到

MZP

这是什么意思?

windows exe 的前几个字节是 DOS header,其结构为:

struct DOS_Header 
 {
     char signature[2] = "MZ";
     short lastsize;
     short nblocks;
     short nreloc;
     short hdrsize;
     short minalloc;
     short maxalloc;
     void *ss;
     void *sp;
     short checksum;
     void *ip;
     void *cs;
     short relocpos;
     short noverlay;
     short reserved1[4];
     short oem_id;
     short oem_info;
     short reserved2[10];
     long  e_lfanew;
 }

将文件作为字符串读取将从 MZ 开始,然后根据您的编码对以下 16 位整数的解释方式而有所不同。如果这些单词中的任何一个的高字节为 0,那也将空终止字符串,这解释了为什么你得到 3 个字符的输出而没有其他任何内容。

具体来说,当lastsize的值为0x3F时,输出MZ?,当lastsize的值为[=17时,输出MZP =].