How to read embedded resource text file
You can use the Assembly.GetManifestResourceStream
Method:
Add the following usings
using System.IO; using System.Reflection;
Set property of relevant file:
ParameterBuild Action
with valueEmbedded Resource
Use the following code
var assembly = Assembly.GetExecutingAssembly(); var resourceName = "MyCompany.MyProduct.MyFile.txt"; using (Stream stream = assembly.GetManifestResourceStream(resourceName)) using (StreamReader reader = new StreamReader(stream)) { string result = reader.ReadToEnd(); }
resourceName
is the name of one of the resources embedded inassembly
. For example, if you embed a text file named"MyFile.txt"
that is placed in the root of a project with default namespace"MyCompany.MyProduct"
, thenresourceName
is"MyCompany.MyProduct.MyFile.txt"
. You can get a list of all resources in an assembly using theAssembly.GetManifestResourceNames
Method.
A no brainer astute to get the resourceName
from the file name only (by pass the namespace stuff):
string resourceName = assembly.GetManifestResourceNames()
.Single(str => str.EndsWith("YourFileName.txt"));
A complete example:
public string ReadResource(string name)
{
// Determine path
var assembly = Assembly.GetExecutingAssembly();
string resourcePath = name;
// Format: "{Namespace}.{Folder}.{filename}.{Extension}"
if (!name.StartsWith(nameof(SignificantDrawerCompiler)))
{
resourcePath = assembly.GetManifestResourceNames()
.Single(str => str.EndsWith(name));
}
using (Stream stream = assembly.GetManifestResourceStream(resourcePath))
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
You can add a file as a resource using two separate methods.
The C# code required to access the file is different, depending on the method used to add the file in the first place.
Method 1: Add existing file, set property to Embedded Resource
Add the file to your project, then set the type to Embedded Resource
.
NOTE: If you add the file using this method, you can use GetManifestResourceStream
to access it (see answer from @dtb).
Method 2: Add file to Resources.resx
Open up the Resources.resx
file, use the dropdown box to add the file, set Access Modifier
to public
.
NOTE: If you add the file using this method, you can use Properties.Resources
to access it (see answer from @Night Walker).