You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
74 lines
2.0 KiB
74 lines
2.0 KiB
3 years ago
|
using System.Reflection;
|
||
4 years ago
|
using System.Text;
|
||
|
|
||
2 years ago
|
namespace Recyclarr.Common;
|
||
3 years ago
|
|
||
|
public class ResourceDataReader
|
||
4 years ago
|
{
|
||
3 years ago
|
private readonly Assembly? _assembly;
|
||
|
private readonly string? _namespace;
|
||
|
private readonly string _subdirectory;
|
||
|
|
||
2 years ago
|
public ResourceDataReader(Assembly assembly, string subdirectory = "")
|
||
|
{
|
||
|
_subdirectory = subdirectory;
|
||
|
_assembly = assembly;
|
||
|
}
|
||
|
|
||
3 years ago
|
public ResourceDataReader(Type typeWithNamespaceToUse, string subdirectory = "")
|
||
4 years ago
|
{
|
||
3 years ago
|
_subdirectory = subdirectory;
|
||
|
_namespace = typeWithNamespaceToUse.Namespace;
|
||
|
_assembly = Assembly.GetAssembly(typeWithNamespaceToUse);
|
||
|
}
|
||
4 years ago
|
|
||
3 years ago
|
public string ReadData(string filename)
|
||
2 years ago
|
{
|
||
|
var resourcePath = BuildResourceName(filename);
|
||
|
var foundResource = FindResourcePath(resourcePath);
|
||
|
return GetResourceData(foundResource);
|
||
|
}
|
||
|
|
||
|
private string BuildResourceName(string filename)
|
||
3 years ago
|
{
|
||
|
var nameBuilder = new StringBuilder();
|
||
2 years ago
|
|
||
|
if (!string.IsNullOrEmpty(_namespace))
|
||
|
{
|
||
|
nameBuilder.Append($"{_namespace}.");
|
||
|
}
|
||
|
|
||
3 years ago
|
if (!string.IsNullOrEmpty(_subdirectory))
|
||
4 years ago
|
{
|
||
2 years ago
|
nameBuilder.Append($"{_subdirectory}.");
|
||
4 years ago
|
}
|
||
|
|
||
2 years ago
|
nameBuilder.Append(filename);
|
||
|
return nameBuilder.ToString();
|
||
|
}
|
||
4 years ago
|
|
||
2 years ago
|
private string FindResourcePath(string resourcePath)
|
||
|
{
|
||
|
var foundResource = _assembly?.GetManifestResourceNames()
|
||
|
.FirstOrDefault(x => x.EndsWith(resourcePath));
|
||
|
if (foundResource is null)
|
||
|
{
|
||
|
throw new ArgumentException($"Embedded resource not found: {resourcePath}");
|
||
|
}
|
||
|
|
||
|
return foundResource;
|
||
|
}
|
||
|
|
||
|
private string GetResourceData(string resourcePath)
|
||
|
{
|
||
|
using var stream = _assembly?.GetManifestResourceStream(resourcePath);
|
||
|
if (stream is null)
|
||
3 years ago
|
{
|
||
2 years ago
|
throw new ArgumentException($"Unable to open embedded resource: {resourcePath}");
|
||
4 years ago
|
}
|
||
3 years ago
|
|
||
|
using var reader = new StreamReader(stream);
|
||
|
return reader.ReadToEnd();
|
||
4 years ago
|
}
|
||
|
}
|