[노트] C# 파일의 MIME Type을 가져오는 방법

2972 단어
MIME Type은 무엇입니까? MIME 참조 안내서 sv.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types
일반적인 방식
파일 접미사 이름이 있는 경우 MimeMapping을 사용할 수 있습니다.GetMimeMapping을 가져옵니다.
MimeMapping.GetMimeMapping(String) Method (System.Web) | Microsoft Docs
만약 MimeMapping이GetMimeMapping이 인식하지 않으면 기본값인 application/octet-stream이 반환됩니다.
기타 방식
특정 유형의 파일에는 Image와 같은 다른 방법으로 가져올 수 있습니다.
public bool TryBuildFileMimeType(string filePath, out string mimeType)
{
    if (string.IsNullOrWhiteSpace(filePath) || !System.IO.File.Exists(filePath))
    {
        mimeType = string.Empty;
        return false;
    }
    try
    {
        var image = Image.FromFile(filePath);
        mimeType = GetMimeTypeFromImage(image);
        return !string.IsNullOrWhiteSpace(mimeType);
    }
    catch (Exception ex)
    {
        mimeType = string.Empty;
        return false;
    }
}

private string GetMimeTypeFromImage(Image image)
{
    if (image.RawFormat.Equals(ImageFormat.Jpeg))
        return "image/jpeg";
    else if (image.RawFormat.Equals(ImageFormat.Bmp))
        return "image/bmp";
    else if (image.RawFormat.Equals(ImageFormat.Emf))
        return "image/emf";
    else if (image.RawFormat.Equals(ImageFormat.Exif))
        return "image/exif";
    else if (image.RawFormat.Equals(ImageFormat.Gif))
        return "image/gif";
    else if (image.RawFormat.Equals(ImageFormat.Icon))
        return "image/icon";
    else if (image.RawFormat.Equals(ImageFormat.Png))
        return "image/png";
    else if (image.RawFormat.Equals(ImageFormat.Tiff))
        return "image/tiff";
    else if (image.RawFormat.Equals(ImageFormat.Wmf))
        return "image/wmf";
    return string.Empty;
}

내가 있는 이곳의 실제 장면에서 대부분의 파일은 접미사 이름이 있다. 즉, MimeMapping으로 처리할 수 있고 접미사 이름이 없는 파일은 모두 그림 파일이고 뒤에 이런 방식으로 처리할 수 있다.
물론 헤더 내용에 따라 파일 형식을 가져와 대응하는 MIME Type을 찾을 수도 있다.그러나 이것은 파일 헤더 표지를 스스로 유지해야 하는 시계인데 기존의 NUGET가 사용할 수 있는지 없는지 추천해 주십시오.
관련 도구
5 Tools To Help Identify Unrecognized or Unknown File Types • Raymond.CC
ExifTool 이 도구는 매우 강력해서 많은 파일 메타데이터 정보를 볼 수 있으며 명령행 버전과 GUI 버전이 있다.
ExifTool by Phil HarveyExifToolGUI
기타
How can I determine file type without an extension on Windows? -Super User, 파일 내용에 따라 파일을 가져오는 유형/MIME type은 본질적으로 믿을 수 없는 것입니까?맞히는 수밖에 없어요?대부분의 흔한 파일 형식에 대해 고정된 형식이 있을 뿐입니까?
어쨌든 파일의 내용이 무엇인지는 개발자가 마음대로 제어할 수 있다.
참조 링크 또는 관련 링크:
  • c# - Get ImageFormat from System.Drawing.Image.RawFormat - Stack Overflow
  • c# - Guessing a file type based on its content - Code Review Stack Exchange
  • .NET 파일의 MIME 유형 가져오기(Content Type)
  • Get a File Content-Type/MIME-type from file extension in ASP.NET C#
  • NuGet Gallery | MimeMapping 1.0.1.17

  • 텍스트 링크:https://www.cnblogs.com/jasongrass/p/11635454.html
    전재 대상:https://www.cnblogs.com/jasongrass/p/11635454.html

    좋은 웹페이지 즐겨찾기