forked from zone117x/MimeMapping
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MimeUtility.cs
63 lines (52 loc) · 2.39 KB
/
MimeUtility.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
namespace MimeMapping
{
/// <summary>
/// MIME type utility to lookup by file extension
/// </summary>
public static class MimeUtility
{
/// <summary>
/// The "octet-stream" subtype is used to indicate that a body contains arbitrary binary data.
/// See <a href="https://www.iana.org/assignments/media-types/application/octet-stream">application/octet-stream</a>
/// </summary>
public const string UnknownMimeType = "application/octet-stream";
static Lazy<ReadOnlyDictionary<string, string>> _lazyDict = new Lazy<ReadOnlyDictionary<string, string>>(
() => new ReadOnlyDictionary<string, string>(KnownMimeTypes.ALL_EXTS.Value.ToDictionary(e => e, e => KnownMimeTypes.LookupType(e)))
);
/// <summary>
/// Dictionary of all available types (lazy loaded on first call)
/// </summary>
public static ReadOnlyDictionary<string, string> TypeMap => _lazyDict.Value;
/// <param name="file">The file extensions (ex: "zip"), the file name, or file path</param>
/// <returns>The mime type string, returns "application/octet-stream" if no known type was found</returns>
public static string GetMimeMapping(string file)
{
if (file == null)
throw new ArgumentNullException(nameof(file));
if (string.IsNullOrEmpty(file))
return UnknownMimeType;
var fileExtension = file.Contains(".")
? GetExtension(file)
: file;
return KnownMimeTypes.LookupType(fileExtension.ToLowerInvariant()) ?? UnknownMimeType;
}
/// <param name="mimeType">The mime type string, e.g. "application/json"</param>
/// <returns>One or more extensions matching the mime type or null if no match</returns>
public static string[] GetExtensions(string mimeType)
{
if (string.IsNullOrEmpty(mimeType)) throw new ArgumentNullException(mimeType);
return KnownMimeTypes.LookupMimeType(mimeType);
}
private static string GetExtension(string path)
{
var extension = Path.GetExtension(path);
if (string.IsNullOrEmpty(extension))
return string.Empty;
return extension.Substring(1);
}
}
}