platform_mime_util_win.cc 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "net/base/platform_mime_util.h"
  5. #include <string>
  6. #include "base/strings/utf_string_conversions.h"
  7. #include "base/win/registry.h"
  8. #include <windows.h>
  9. namespace net {
  10. bool PlatformMimeUtil::GetPlatformMimeTypeFromExtension(
  11. const base::FilePath::StringType& ext, std::string* result) const {
  12. // check windows registry for file extension's mime type (registry key
  13. // names are not case-sensitive).
  14. base::FilePath::StringType value, key = FILE_PATH_LITERAL(".") + ext;
  15. base::win::RegKey(HKEY_CLASSES_ROOT, key.c_str(), KEY_READ)
  16. .ReadValue(L"Content Type", &value);
  17. if (!value.empty()) {
  18. *result = base::WideToUTF8(value);
  19. return true;
  20. }
  21. return false;
  22. }
  23. bool PlatformMimeUtil::GetPlatformPreferredExtensionForMimeType(
  24. const std::string& mime_type,
  25. base::FilePath::StringType* ext) const {
  26. base::FilePath::StringType key =
  27. L"MIME\\Database\\Content Type\\" + base::UTF8ToWide(mime_type);
  28. if (base::win::RegKey(HKEY_CLASSES_ROOT, key.c_str(), KEY_READ)
  29. .ReadValue(L"Extension", ext) != ERROR_SUCCESS) {
  30. return false;
  31. }
  32. // Strip off the leading dot, this should always be the case.
  33. if (!ext->empty() && ext->front() == '.')
  34. ext->erase(ext->begin());
  35. return true;
  36. }
  37. void PlatformMimeUtil::GetPlatformExtensionsForMimeType(
  38. const std::string& mime_type,
  39. std::unordered_set<base::FilePath::StringType>* extensions) const {
  40. // Multiple extensions could have the given mime type specified as their types
  41. // in their 'HKCR\.<extension>\Content Type' keys. Iterating all the HKCR
  42. // entries, though, is wildly impractical. Cheat by returning just the
  43. // preferred extension.
  44. base::FilePath::StringType ext;
  45. if (GetPlatformPreferredExtensionForMimeType(mime_type, &ext))
  46. extensions->insert(ext);
  47. }
  48. } // namespace net