@@ -50,6 +50,52 @@ public static string GetMimeType(string extension)
5050 private static readonly Regex CalendarPattern = new ( @"^(?:text/calendar|application/ics)$" , RegexOptions . Compiled | RegexOptions . IgnoreCase ) ;
5151 private static readonly Regex EmailPattern = new ( @"^(?:message/(?:rfc822|global)|application/(?:mbox|x-msmessage))" , RegexOptions . Compiled | RegexOptions . IgnoreCase ) ;
5252
53+ private static readonly Dictionary < byte [ ] , string > MimeTypesForContent = new ( )
54+ {
55+ { new byte [ ] { 0x25 , 0x50 , 0x44 , 0x46 } , "application/pdf" } , // PDF
56+ { new byte [ ] { 0xFF , 0xD8 , 0xFF } , "image/jpeg" } , // JPEG
57+ { new byte [ ] { 0x89 , 0x50 , 0x4E , 0x47 } , "image/png" } , // PNG
58+ { new byte [ ] { 0x47 , 0x49 , 0x46 , 0x38 } , "image/gif" } , // GIF
59+ { new byte [ ] { 0x50 , 0x4B , 0x03 , 0x04 } , "application/zip" } , // ZIP
60+ { new byte [ ] { 0x1F , 0x8B } , "application/gzip" } // GZIP
61+ } ;
62+
63+ public static string GetMimeTypeByContent ( string filePath )
64+ {
65+ byte [ ] fileHeader = new byte [ 4 ] ;
66+ using ( FileStream fs = new FileStream ( filePath , FileMode . Open , FileAccess . Read ) )
67+ {
68+ fs . ReadExactly ( fileHeader , 0 , fileHeader . Length ) ;
69+ }
70+
71+ foreach ( var mime in MimeTypes )
72+ {
73+ if ( fileHeader . AsSpan ( ) . Slice ( 0 , mime . Key . Length ) . SequenceEqual ( mime . Key ) )
74+ {
75+ return mime . Value ;
76+ }
77+ }
78+
79+ return "application/octet-stream" ; // Default MIME type
80+ }
81+
82+ public static string GetMimeTypeByContent ( Stream fileStream )
83+ {
84+ byte [ ] fileHeader = new byte [ 4 ] ;
85+ fileStream . ReadExactly ( fileHeader , 0 , fileHeader . Length ) ;
86+
87+ foreach ( var mime in MimeTypes )
88+ {
89+ if ( fileHeader . AsSpan ( ) . Slice ( 0 , mime . Key . Length ) . SequenceEqual ( mime . Key ) )
90+ {
91+ return mime . Value ;
92+ }
93+ }
94+
95+ return "application/octet-stream" ; // Default MIME type
96+ }
97+
98+
5399 public static MimeTypeCategory GetMimeCategory ( string mime )
54100 {
55101 if ( string . IsNullOrWhiteSpace ( mime ) )
0 commit comments