How to Access a File's Properties on Windows

Reading file properties from windows file system?

Some of that is already avaiable in FileInfo (Length is the file size, Date Modified is simply LastWriteTime). Some of the information is available from FileVersionInfo. The 'type' is kind of tricky, but this post has some info on looking the mime type up in the registry. This worked for me on windows 7:

private static string GetType(string fileName)
{
string type = "Unknown";
string ext = System.IO.Path.GetExtension(fileName).ToLower();
Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (regKey != null && regKey.GetValue("") != null)
{
string lookup = regKey.GetValue("").ToString();
if (!string.IsNullOrEmpty(lookup))
{
var lookupKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(lookup);
if (lookupKey != null)
{
type = lookupKey.GetValue("").ToString();
}
}
}
return type;
}

It will produce the Type you see in detail tab page of the file properties. For example, 'Application' for exe and 'Bitmap Image' for bmp.

The answer here gets the type using the windows api function shgetfileinfo.

How to get file's properties from Windows' registry?

OK, so I found out how to do it... This code checks the file type (or association) by looking in the Windows' registry (the same as opening regedit, going in HKEY_CLASSES_ROOT and then looking at the keys in there, as the user @martineau suggested):

rawcom = os.popen("assoc ."+command[len(command)-1]).read().split("=")

It is already split, so I can do rawcom[1] and get the file type easily.
If there isn't a file association in the Windows' registry, it checks the file type using this code that I found:

def get_file_metadata(path, filename, metadata):
sh = win32com.client.gencache.EnsureDispatch('Shell.Application', 0)
ns = sh.NameSpace(path)
file_metadata = dict()
item = ns.ParseName(str(filename))
for ind, attribute in enumerate(metadata):
attr_value = ns.GetDetailsOf(item, ind)
if attr_value:
file_metadata[attribute] = attr_value
return file_metadata

if __name__ == '__main__':
folder = direc
filename = file
metadata = ['Name', 'Size', 'Item type', 'Date modified', 'Date created']
proprietà = get_file_metadata(folder, filename, metadata)

It does exactly what I was trying to do at the start, getting the file type as if I was opening the file's properties in the Windows explorer. With this I put the file metadata in a dictionary and then get only the "Item type" value.



Related Topics



Leave a reply



Submit