-
Notifications
You must be signed in to change notification settings - Fork 23
/
EmbeddedContentProvider.cs
78 lines (68 loc) · 2.84 KB
/
EmbeddedContentProvider.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
namespace SpiderEye
{
/// <summary>
/// Content provider for files that are embedded in an assembly.
/// </summary>
public class EmbeddedContentProvider : IContentProvider
{
private readonly Assembly contentAssembly;
private readonly Dictionary<string, string> fileMap;
/// <summary>
/// Initializes a new instance of the <see cref="EmbeddedContentProvider"/> class.
/// </summary>
/// <param name="contentFolder">Gets or sets the folder path where the embedded files are.</param>
public EmbeddedContentProvider(string contentFolder)
: this(contentFolder, Assembly.GetCallingAssembly())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EmbeddedContentProvider"/> class.
/// </summary>
/// <param name="contentFolder">Gets or sets the folder path where the embedded files are.</param>
/// <param name="contentAssembly">Gets or sets the assembly where the content files are embedded.</param>
public EmbeddedContentProvider(string contentFolder, Assembly contentAssembly)
{
if (contentFolder == null) { throw new ArgumentNullException(nameof(contentFolder)); }
this.contentAssembly = contentAssembly ?? throw new ArgumentNullException(nameof(contentAssembly));
fileMap = CreateFileMap(contentAssembly, contentFolder);
}
/// <inheritdoc/>
public Task<Stream?> GetStreamAsync(Uri uri)
{
Stream? result = null;
string path = uri.GetComponents(UriComponents.Path, UriFormat.Unescaped).ToLower();
if (fileMap.TryGetValue(path, out string? file))
{
try { result = contentAssembly.GetManifestResourceStream(file); }
catch (FileNotFoundException) { result = null; }
}
return Task.FromResult(result);
}
private Dictionary<string, string> CreateFileMap(Assembly contentAssembly, string contentFolder)
{
contentFolder = NormalizePath(contentFolder);
string[] files = contentAssembly.GetManifestResourceNames();
var dict = new Dictionary<string, string>();
foreach (string file in files)
{
string key = NormalizePath(file);
if (key.StartsWith(contentFolder))
{
dict.Add(key[contentFolder.Length..].TrimStart('/'), file);
}
}
return dict;
}
private static string NormalizePath(string path)
{
return path.Replace('\\', '/')
.TrimStart('/')
.ToLower();
}
}
}