-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathMimeUtilities.cs
97 lines (80 loc) · 3.09 KB
/
MimeUtilities.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
//-----------------------------------------------------------------------
// <copyright file="MimeUtilities.cs" company="(none)">
// Copyright © 2013 John Gietzen and the WebGit .NET Authors. All rights reserved.
// </copyright>
// <author>John Gietzen</author>
//-----------------------------------------------------------------------
namespace WebGitNet
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Microsoft.Win32;
public class MimeUtilities
{
private static readonly Dictionary<string, string> knownExtensions = new Dictionary<string, string>();
private static readonly Dictionary<string, string> knownNames = new Dictionary<string, string>();
static MimeUtilities()
{
var assemblyPath = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);
try
{
foreach (var line in File.ReadAllLines(Path.Combine(assemblyPath, "mime-types.txt")))
{
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
var parts = line.Split(new[] { ':' }, 2);
var file = parts[0].ToLowerInvariant();
var type = parts[1].ToLowerInvariant();
if (file.StartsWith("."))
{
knownExtensions[file] = type;
}
else
{
knownNames[file] = type;
}
}
}
catch (IOException)
{
}
}
public static string GetMimeType(string fileName)
{
string value;
fileName = Path.GetFileName(fileName.ToLowerInvariant());
if (knownNames.TryGetValue(fileName, out value))
{
return value;
}
string extension = Path.GetExtension(fileName);
if (!string.IsNullOrEmpty(extension))
{
if (knownExtensions.TryGetValue(extension, out value))
{
return value;
}
value = Registry.GetValue(@"HKEY_CLASSES_ROOT\" + extension, "ContentType", string.Empty) as string;
if (!string.IsNullOrEmpty(value))
{
return value.ToLowerInvariant();
}
value = Registry.GetValue(@"HKEY_CLASSES_ROOT\" + extension, "Content Type", string.Empty) as string;
if (!string.IsNullOrEmpty(value))
{
return value.ToLowerInvariant();
}
value = Registry.GetValue(@"HKEY_CLASSES_ROOT\" + extension, "PerceivedType", string.Empty) as string;
if (!string.IsNullOrEmpty(value))
{
return value.ToLowerInvariant() + "/unknown";
}
}
return "application/octet-stream";
}
}
}