#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Net" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>
<# var mediaTypes = GetMediaTypeList(); #>
//
namespace <#=System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("NamespaceHint").ToString()#>
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
///
/// Provides utilities for mapping file names and extensions to MIME-types.
///
[CompilerGenerated]
[DebuggerNonUserCode]
public static class MimeTypes
{
///
/// The fallback MIME-type. Defaults to application/octet-stream.
///
public static string FallbackMimeType { get; set; }
private static readonly Dictionary TypeMap;
static MimeTypes()
{
FallbackMimeType = "application/octet-stream";
TypeMap = new Dictionary(StringComparer.OrdinalIgnoreCase)
{
<# foreach (var mediaType in mediaTypes) { #>
{ "<#= mediaType.Item1 #>", "<#= mediaType.Item2 #>" },
<# } #>
};
}
///
/// Gets the MIME-type for the given file name,
/// or if a mapping doesn't exist.
///
/// The name of the file.
/// The MIME-type for the given file name.
public static string GetMimeType(string fileName)
{
var dotIndex = fileName.LastIndexOf('.');
return dotIndex != -1 &&
fileName.Length > dotIndex + 1 &&
TypeMap.TryGetValue(fileName.Substring(dotIndex + 1), out var result)
? result
: FallbackMimeType;
}
}
}
<#+
private static IList> GetMediaTypeList()
{
using (var client = new WebClient())
{
var list = client.DownloadString(new Uri("http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types"));
var lines = SplitString(list, '\r', '\n');
return GetMediaTypes(lines).ToList();
}
}
private static IEnumerable> GetMediaTypes(IEnumerable lines)
{
return lines.Where(x => !x.StartsWith("#"))
.Select(line => SplitString(line, '\t', ' '))
.SelectMany(CreateMediaTypes)
.GroupBy(x => x.Item1)
.Where(x => x.Count() == 1)
.Select(x => x.Single())
.OrderBy(x => x.Item1);
}
private static string[] SplitString(string line, params char[] separator)
{
return line.Split(separator, StringSplitOptions.RemoveEmptyEntries);
}
private static IEnumerable> CreateMediaTypes(string[] parts)
{
return parts.Skip(1).Select(extension => Tuple.Create(extension, parts.First()));
}
#>