How to find if a file is an exe?

后端 未结 6 1771
粉色の甜心
粉色の甜心 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:29

    A very primitive check would be to check for the file extension:

    Path.GetExtension(filename).Equals(".exe", 
        StringComparison.InvariantCultureIgnoreCase);
    

    However, Windows supports a variety of extensions for executable files (e.g. .cmd, .com, .cpl, .scr and many more), so the check above would not cover all executable files.

    As mentioned by others, you can also check the magic numbers in the file header for the existence of e.g. MZ (and some other more rare signatures). This second check could be used in addition to checking the extension(s) though you can never be certain that the file is not a simple text file accidentally starting with the same text.

    If you are going to start the executable to be checked anyway, then it is probably safest to simply start it with proper exception handling:

    const int ERROR_BAD_EXE_FORMAT = 193;
    try
    {
        ProcessStartInfo psi = new ProcessStartInfo();
        psi.UseShellExecute = false;
        psi.FileName = @"C:\tmp\testOLElocal_4.docx";
        Process.Start(psi);
    }
    catch (Win32Exception ex)
    {
        if (ex.NativeErrorCode == ERROR_BAD_EXE_FORMAT)
        {
            // The exception message would be
            // "The specified executable is not a valid application for this OS platform."
            //
            Console.WriteLine("Not a valid executable.");
        }
        else
        {
            throw;
        }
    }
    

    NB: You didn't mention any details about your own application, but whenever executing code which comes via user input you should make sure that your user can be trusted.

提交回复
热议问题