How to open file from resources C#

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

Answers


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;
    }


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.


Need Your Help

How to test website for larger displays?

html css responsive-design

I need to test my website in 1920px X 1200px and smart tv also.

Can I return a parsed XML path with XML::Simple?

perl xml-parsing

I have an XML file that has the following format:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.