[노트] C# 파일의 MIME Type을 가져오는 방법
일반적인 방식
파일 접미사 이름이 있는 경우 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은 본질적으로 믿을 수 없는 것입니까?맞히는 수밖에 없어요?대부분의 흔한 파일 형식에 대해 고정된 형식이 있을 뿐입니까?
어쨌든 파일의 내용이 무엇인지는 개발자가 마음대로 제어할 수 있다.
참조 링크 또는 관련 링크:
텍스트 링크:https://www.cnblogs.com/jasongrass/p/11635454.html
전재 대상:https://www.cnblogs.com/jasongrass/p/11635454.html
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.