Skip to content

Instantly share code, notes, and snippets.

@jakesays-old
Last active June 13, 2017 11:21
Show Gist options
  • Save jakesays-old/469311a6761aab26d2be0e6d9ef7acde to your computer and use it in GitHub Desktop.
Save jakesays-old/469311a6761aab26d2be0e6d9ef7acde to your computer and use it in GitHub Desktop.
Test resource helper class
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Text;
namespace Std.TestingSupport
{
public class TestDataManager
{
private readonly Assembly _sourceAssembly;
private readonly List<TestResource> _resources;
class TestResource
{
public string ResourceKey { get; private set; }
public string Name { get; private set; }
public string Text { get; private set; }
public byte[] Data { get; private set; }
public bool Loaded { get; private set; }
public TestResource(string resourceKey, string name)
{
ResourceKey = resourceKey;
Name = name;
}
public void SetText(string text)
{
Loaded = true;
Text = text;
}
public void SetData(byte[] data)
{
Loaded = true;
Data = data;
}
}
private const string ResourceBaseName = /* full namespace path to your test files, which is assy namespace + directory structure relative to project file */
public TestDataManager()
{
_sourceAssembly = Assembly.GetExecutingAssembly();
_resources = _sourceAssembly.GetManifestResourceNames()
.Select(s => new TestResource(s, s.ToLowerInvariant())).ToList();
}
public byte[] LoadBinaryFile(string name)
{
name = (ResourceBaseName + name).ToLowerInvariant();
var resource = _resources.FirstOrDefault(r => r.Name == name);
if (resource == null)
{
throw new MissingManifestResourceException(name);
}
if (!resource.Loaded)
{
using (var rstream = _sourceAssembly.GetManifestResourceStream(resource.ResourceKey))
{
var size = (int) rstream.Length;
var data = new byte[size];
rstream.Read(data, 0, size);
resource.SetData(data);
}
}
return resource.Data;
}
public string LoadTextFile(string name)
{
name = (ResourceBaseName + name).ToLowerInvariant();
var resource = _resources.FirstOrDefault(r => r.Name == name);
if (resource == null)
{
throw new MissingManifestResourceException(name);
}
if (!resource.Loaded)
{
using (var rstream = _sourceAssembly.GetManifestResourceStream(resource.ResourceKey))
using (var reader = new StreamReader(rstream, Encoding.UTF8))
{
var data = reader.ReadToEnd();
resource.SetText(data);
}
}
return resource.Text;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment