Do You know how to open file from resources in Visual studio when I click on a button? Thanks.
Asked
Active
Viewed 1.6k times
1
-
2When you click on a button in Visual Studio? Or when you click on button on keyboard? Or when you click on a button on page create by ASP.Net? Or button on WinForm? (Note that there are search engines that can save you time - "load from resources C#" is not rare search request. Advertisement: you can use http://www.bing.com to search). – Alexei Levenkov Sep 08 '12 at 18:24
-
Changing the meaning of a question isn't really acceptable. I've rolled this back to the original. Please don't do this again. Thanks. – Kev Sep 08 '12 at 23:30
2 Answers
13
You could use the GetManifestResourceStream method:
var currentAssembly = Assembly.GetExecutingAssembly();
using (var stream = currentAssembly.GetManifestResourceStream("SomeNs.file.txt"))
using (var reader = new StreamReader(stream))
{
// TODO: read the stream here
string contents = reader.ReadToEnd();
}
In this example file.txt
is embedded into the current assembly as resource. You will have to adjust the name of the resource you are trying to read. And don't use a StreamReader
if the embedded resource is not a text file. You will have to read the stream directly if it is a binary file.

Darin Dimitrov
- 1,023,142
- 271
- 3,287
- 2,928
0
this can be used when your file is a local file
string resName = "myfile.txt";
var file = GetResourceStream(resName);
string all = "";
using (var reader = new StreamReader(file))
{
all = reader.ReadToEnd();
}
where
static UnmanagedMemoryStream GetResourceStream(string resName)
{
var assembly = Assembly.GetExecutingAssembly();
var strResources = assembly.GetName().Name + ".g.resources";
var rStream = assembly.GetManifestResourceStream(strResources);
var resourceReader = new System.Resources.ResourceReader(rStream);
var items = resourceReader.OfType<System.Collections.DictionaryEntry>();
var stream = items.First(x => (x.Key as string) == resName.ToLower()).Value;
return (UnmanagedMemoryStream)stream;
}