-
Notifications
You must be signed in to change notification settings - Fork 0
/
_ReadEmbeddedResource.cs
81 lines (63 loc) · 2.83 KB
/
_ReadEmbeddedResource.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
using System;
using System.IO;
using System.Text;
namespace SystemLibrary.Common.Net
{
partial class Assemblies
{
static byte[] ReadEmbeddedResourceAsBytes(string folderPathInProject, string fileName, System.Reflection.Assembly asm)
{
byte[] ReadResourceFromAssemblyStream(string path)
{
using (Stream stream = asm.GetManifestResourceStream(path))
{
if (stream == null) return null;
if (stream.Length > int.MaxValue)
throw new Exception("The embedded resource is too large, max bytes supported is: " + int.MaxValue);
var bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
return bytes;
}
}
string resourcePath = GetResourcePath(folderPathInProject, fileName, asm);
return ReadResourceFromAssemblyStream(resourcePath);
}
static string ReadEmbeddedResourceAsString(string folderPathInProject, string fileName, System.Reflection.Assembly asm)
{
string ReadResourceFromAssemblyStream(string path)
{
using (Stream stream = asm.GetManifestResourceStream(path))
{
if (stream == null) return null;
using (var reader = new StreamReader(stream))
return reader.ReadToEnd();
}
}
string resourcePath = GetResourcePath(folderPathInProject, fileName, asm);
return ReadResourceFromAssemblyStream(resourcePath);
}
static string GetResourcePath(string folderPathInProject, string fileName, System.Reflection.Assembly asm)
{
bool UseAsmNameAsRootResourcePath(string assemblyNamespace)
{
return folderPathInProject.IsNot() ||
(assemblyNamespace.Is() && !assemblyNamespace.StartsWith(folderPathInProject.Split('.')[0]));
}
StringBuilder resourcePath = new StringBuilder();
var defaultAsmNamespace = asm?.FullName.Split(',')[0];
if (UseAsmNameAsRootResourcePath(defaultAsmNamespace))
resourcePath.Append(defaultAsmNamespace + "." +
(folderPathInProject.IsNot() ? "" : folderPathInProject + "."));
else if (folderPathInProject?.EndsWith(".") == true)
resourcePath.Append(folderPathInProject);
else
resourcePath.Append(folderPathInProject + ".");
if (folderPathInProject.Is())
resourcePath?
.Replace("/", ".")
.Replace("\\", ".");
resourcePath.Append(fileName);
return resourcePath.ToString();
}
}
}