-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
EmbeddedResource.cs
47 lines (39 loc) · 1.65 KB
/
EmbeddedResource.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
using System;
using System.IO;
using System.Linq;
using System.Reflection;
static class EmbeddedResource
{
static readonly string baseDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? "";
public static string GetContent(string relativePath)
{
using var stream = GetStream(relativePath);
using var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
public static byte[] GetBytes(string relativePath)
{
using var stream = GetStream(relativePath);
var bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
return bytes;
}
public static Stream GetStream(string relativePath)
{
var filePath = Path.Combine(baseDir, Path.GetFileName(relativePath));
if (File.Exists(filePath))
return File.OpenRead(filePath);
var baseName = Assembly.GetExecutingAssembly().GetName().Name;
var resourceName = relativePath
.TrimStart('.')
.Replace('/', '.')
.Replace('\\', '.');
var manifestResourceName = Assembly.GetExecutingAssembly()
.GetManifestResourceNames().FirstOrDefault(x => x.EndsWith(resourceName));
if (string.IsNullOrEmpty(manifestResourceName))
throw new InvalidOperationException($"Did not find required resource ending in '{resourceName}' in assembly '{baseName}'.");
return
Assembly.GetExecutingAssembly().GetManifestResourceStream(manifestResourceName) ??
throw new InvalidOperationException($"Did not find required resource '{manifestResourceName}' in assembly '{baseName}'.");
}
}