Is there any way to can get the MIME Type in C++ given a file extension?
I have read about HKEY_CLASSES_ROOT, but I honestly have no idea of how to use it.
What I want is having as input:
string extension=".pdf";
string extension2=".avi";
Get as output:
string mimeType="application/pdf";
string mimeType2="video/x-msvideo";
I know I could do this by myself, but I guess there is some work already done in here.
Thanks a lot
The simplest solution involves calling FindMimeFromData
:
#include <urlmon.h>
#pragma comment( lib, "urlmon" )
std::wstring MimeTypeFromString( const std::wstring& str ) {
LPWSTR pwzMimeOut = NULL;
HRESULT hr = FindMimeFromData( NULL, str.c_str(), NULL, 0,
NULL, FMFD_URLASFILENAME, &pwzMimeOut, 0x0 );
if ( SUCCEEDED( hr ) ) {
std::wstring strResult( pwzMimeOut );
// Despite the documentation stating to call operator delete, the
// returned string must be cleaned up using CoTaskMemFree
CoTaskMemFree( pwzMimeOut );
return strResult;
}
return L"";
}
The following application
int _tmain( int argc, _TCHAR* argv[] ) {
std::wcout << L".pdf: " << MimeTypeFromString( L".pdf" ) << std::endl;
std::wcout << L".avi: " << MimeTypeFromString( L".avi" ) << std::endl;
return 0;
}
produces this output on my system:
.pdf: application/pdf
.avi: video/avi
As it's nearly Christmas, How about this:
#include <Windows.h>
#include <string>
using namespace std;
string GetMimeType(const string &szExtension)
{
// return mime type for extension
HKEY hKey = NULL;
string szResult = "application/unknown";
// open registry key
if (RegOpenKeyEx(HKEY_CLASSES_ROOT, szExtension.c_str(),
0, KEY_READ, &hKey) == ERROR_SUCCESS)
{
// define buffer
char szBuffer[256] = {0};
DWORD dwBuffSize = sizeof(szBuffer);
// get content type
if (RegQueryValueEx(hKey, "Content Type", NULL, NULL,
(LPBYTE)szBuffer, &dwBuffSize) == ERROR_SUCCESS)
{
// success
szResult = szBuffer;
}
// close key
RegCloseKey(hKey);
}
// return result
return szResult;
}
int main(int argc, char* argv[])
{
string szExt1 = ".pdf";
string szExt2 = ".avi";
string szMime1 = GetMimeType(szExt1);
string szMime2 = GetMimeType(szExt2);
printf("%s = %s\n%s = %s\n", szExt1.c_str(), szMime1.c_str(),
szExt2.c_str(), szMime2.c_str());
return 0;
}
On my system, it gives the following output:
.pdf = application/pdf
.avi = video/avi
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.