Using ctypes with Windows API to get FileVersion of a file

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • looping

    #1

    Using ctypes with Windows API to get FileVersion of a file

    Hi,
    I need to get the FileVersion of some files on Windows. The best way
    look like to use function GetFileVersionI nfo from the Windows API. I
    first try with pywin32 and it work well, but with ctypes now included
    in Python 2.5, use it look like a good idea.
    So I write the code below that work fine, but I'm not sure it's the
    best way to do what I want.
    My main concern is about the codepages extraction: could I use a struct
    to make the job ?
    Codepages is actually an array of struct, how could I use ctypes to
    extract it ?

    Thanks for your comments and advices.

    import array
    from ctypes import *

    def get_file_info(f ilename, info):
    """
    Extract information from a file.
    """
    # Get size needed for buffer (0 if no info)
    size = windll.version. GetFileVersionI nfoSizeA(filena me, None)
    # If no info in file -empty string
    if not size:
    return ''
    # Create buffer
    res = create_string_b uffer(size)
    # Load file informations into buffer res
    windll.version. GetFileVersionI nfoA(filename, None, size, res)
    r = c_uint()
    l = c_uint()
    # Look for codepages
    windll.version. VerQueryValueA( res, '\\VarFileInfo\ \Translation',
    byref(r), byref(l))
    # If no codepage -empty string
    if not l.value:
    return ''
    # Take the first codepage (what else ?)
    codepages = array.array('H' , string_at(r.val ue, l.value))
    codepage = tuple(codepages[:2].tolist())
    # Extract information
    windll.version. VerQueryValueA( res, ('\\StringFileI nfo\\%04x%04x\\ '
    + info) % codepage,
    byref(r), byref(l))
    return string_at(r.val ue, l.value)

    print get_file_info(r 'C:\WINDOWS\sys tem32\calc.exe' , 'FileVersion')

Working...