Do You know how to open file from resources in Visual studio when I click on a button? Thanks.
-
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 bing.com to search).Alexei Levenkov– Alexei Levenkov2012-09-08 18:24:46 +00:00Commented Sep 8, 2012 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– Kev2012-09-08 23:30:59 +00:00Commented Sep 8, 2012 at 23:30
Add a comment
|
2 Answers
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.
1 Comment
quantum
+1: This is the correct answer to the question.
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;
}

1 Comment
Shannon
why use UnmanagedMemoryStream?