Skip to content

Instantly share code, notes, and snippets.

@chaojian-zhang
Created November 5, 2022 18:05
Show Gist options
  • Save chaojian-zhang/f8dbb9c87d8d8ce40c5a95525aa65328 to your computer and use it in GitHub Desktop.
Save chaojian-zhang/f8dbb9c87d8d8ce40c5a95525aa65328 to your computer and use it in GitHub Desktop.
A snippet for reading embedded resource. #C# #CSharp #Utility #EmbeddedResource
public string ReadResource(string name)
{
// Determine path
var assembly = Assembly.GetExecutingAssembly();
string resourcePath = name;
// Format: "{Namespace}.{Folder}.{filename}.{Extension}"
if (!name.StartsWith(nameof(YourAssemblyName)))
{
resourcePath = assembly.GetManifestResourceNames()
.Single(str => str.EndsWith(name));
}
using (Stream stream = assembly.GetManifestResourceStream(resourcePath))
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Utility
{
public static class EmbeddedResourceHelper
{
public static Stream ReadBinaryResource(string path)
{
Assembly sourceAssembly = Assembly.GetCallingAssembly();
if (!sourceAssembly.GetManifestResourceNames().Any(str => str == path))
throw new ArgumentException($"Specified resource doesn't exist in assembly {sourceAssembly.GetName()}.");
Stream stream = sourceAssembly.GetManifestResourceStream(path);
return stream;
}
public static string ReadTextResource(string path)
{
Assembly sourceAssembly = Assembly.GetCallingAssembly();
if (!sourceAssembly.GetManifestResourceNames().Any(str => str == path))
throw new ArgumentException($"Specified resource doesn't exist in assembly {sourceAssembly.GetName()}.");
using (Stream stream = sourceAssembly.GetManifestResourceStream(path))
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment