Reputation: 36048
If I add a new text file to my project regexCheck.txt
it's default build action is as Resource:
I know I will be able to retrieve the content of that text file if I set the option to copy to output dicectory = always then I will be able to find it on workingDirectory\Macros\Header\regexCheck.txt
I am just curious on how I will be able to retreive the content of that text file without having to output it to the working directory.
For example relector is able to look at all the resources of my executable:
I know I could place the file in a resource.resx
I am just curious to know how to extract resources from an exe
Doing something like:
var _assembly = Assembly.GetExecutingAssembly();
var resourceName = _assembly.GetManifestResourceNames()[0];
var steam = _assembly.GetManifestResourceStream(resourceName);
var buffer = new byte[2048];
steam.Read(buffer, 0, buffer.Length);
var text = System.Text.ASCIIEncoding.ASCII.GetString(buffer).Replace("\0", "");
I managed to see the contents of my text file:
Upvotes: 2
Views: 1405
Reputation: 36048
I changed the build action from Resource
to Embeded Resource
I was able to get the content by doing:
var fileName = "regexCheck.txt";
var currentNamespace = typeof(this).Namespace; // if static class use name of class
var fullName = currentNamespace + "." + fileName;
Func<string,Stream> getResStream =
x => Assembly.GetExecutingAssembly().GetManifestResourceStream(x);
using (Stream stream = getResStream(fullName))
using (StreamReader reader = new StreamReader(stream))
string result = reader.ReadToEnd(); // <------ Result should be the content of text file
the reason why that code words is because the class and the text file are on the same namespace (same directory and namespace)
Upvotes: 1
Reputation: 32576
I don't think you can using the way you've got the file attached to the project at the moment.
The other way to do it is to add a "Resources File" to the project. (Project -> Add New Item... -> Resources File). You can then add the text file in the resource file designer (Add Resource -> Add existing file...)
You'll end up with a project tree looking something like this:
Project
|
+-- Resources
| |
| +-- regexCheck.txt
|
+-- Resource.resx
| |
| +-- Resource.Designer.cs
In your code Resource.regexCheck
is then a string containing the contents of the file.
Upvotes: 1