1

Do You know how to open file from resources in Visual studio when I click on a button? Thanks.

2
  • 2
    When 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). Commented 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. Commented Sep 8, 2012 at 23:30

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1: This is the correct answer to the question.
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;
    }

enter image description here

1 Comment

why use UnmanagedMemoryStream?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.