How to find if a file is an exe?

后端 未结 6 1772
粉色の甜心
粉色の甜心 2020-12-05 14:51

How can I be sure that a file passed to my program is a valid exe file ?

actually my program takes a file as input and runs it, but user can input any file so I have

6条回答
  •  抹茶落季
    2020-12-05 15:26

    bool IsExeFile(string path)
    {
        var twoBytes = new byte[2];
        using(var fileStream = File.Open(path, FileMode.Open))
        {
            fileStream.Read(twoBytes, 0, 2);
        }
    
        return Encoding.UTF8.GetString(twoBytes) == "MZ";
    }
    

提交回复
热议问题