Joe J
Joe J

Reputation: 359

Get the file type shown in File Explorer

File Explorer has a Type column that indicates the file type. For example, for a file with the extension .txt, the Type column contains Text Document, and for a file with the extension .jpg, this column contains JPG File, and so on.

Is it possible to programmatically get the value from the Type column for a given file using C++?

Upvotes: -1

Views: 76

Answers (1)

Joe J
Joe J

Reputation: 359

Yes, this information is stored in the SHFILEINFOA structure, which can be obtained by calling the SHGetFileInfoA function.

#include <windows.h>
#include <shlobj.h>
#include <iostream>
#include <filesystem>

std::string GetFileType(const std::string& filePath) 
{
    auto fileAttr = std::filesystem::is_directory(filePath) ? FILE_ATTRIBUTE_DIRECTORY : FILE_ATTRIBUTE_NORMAL;

    SHFILEINFOA fileInfo{};
    DWORD_PTR result = SHGetFileInfoA(
        filePath.c_str(),
        fileAttr,
        &fileInfo,
        sizeof(fileInfo),
        SHGFI_TYPENAME | SHGFI_USEFILEATTRIBUTES
    );

    if (result) {
        return fileInfo.szTypeName;
    }
    else {
        return "Unknown file type";
    }
}

int main() {
    std::string filePath = "C:\\Users\\Username\\Desktop\\test.txt";
    std::string fileType = GetFileType(filePath);
    std::cout << "File type: " << fileType << std::endl;
    return 0;
}

Upvotes: 1

Related Questions