Timmy Turner
Timmy Turner

Reputation: 99

Access Embedded Resource In Console App

I am embedding a .docx file into my Console App, and I want to be able to distribute the console.exe and have the users be able to access the .docx file inside it.

I have set the .docx file as a resource (see image) - however, if I try to "access" it by using Resources.Test.docx it seems as it if does not exist, and intellisense is not giving it as an option.

How should I do this in a C# console app? Resource

EDIT
In winforms I would embed as resource like this:

static void Main(string[] args)
{   
    AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
    {
        string rn1 = new AssemblyName(args.Name).Name + ".docx";
        string rs1 = Array.Find(this.GetType().Assembly.GetManifestResourceNames(), element => element.EndsWith(rn1));

        using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(rs1))
        {
            Byte[] assemblydata = new Byte[stream.Length];
            stream.Read(assemblydata, 0, assemblydata.Length);
            return Assembly.Load(assemblydata);
        }
    }
}

And access the file like this:

Object oFName;
byte[] resourceFile = Properties.Resources.Report;
string destination = Path.Combine(Path.GetTempPath(), "Test.docx");
System.IO.File.WriteAllBytes(destination, resourceFile);
oFName = destination;

EDIT 2
If I try to use the code I use for winforms the AppDomain.CurrentDomain.AssemblyResolve -> I receive the below errors

A local or parameter named 'args' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
Keyword 'this' is not valid in a static property, static method, or static field initializer

Upvotes: 2

Views: 1478

Answers (1)

Ron Beyer
Ron Beyer

Reputation: 11273

Your first method, with a little bit of modification, should be able to return a resource stream. Here is basically what you have modified a little bit to just read the stream:

    public static byte[] GetResourceData(string resourceName)
    {
        var embeddedResource = Assembly.GetExecutingAssembly().GetManifestResourceNames().FirstOrDefault(s => string.Compare(s, resourceName, true) == 0);

        if (!string.IsNullOrWhiteSpace(embeddedResource))
        {
            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedResource))
            {
                var data = new byte[stream.Length];
                stream.Read(data, 0, data.Length);

                return data;
            }
        }

        return null;
    }

This method can be called using the resource name and will return all the bytes that are inside the embedded resource.

Upvotes: 3

Related Questions