Created
November 5, 2022 18:05
-
-
Save chaojian-zhang/f8dbb9c87d8d8ce40c5a95525aa65328 to your computer and use it in GitHub Desktop.
A snippet for reading embedded resource. #C# #CSharp #Utility #EmbeddedResource
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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