1

I have an embedded resource named "Test.exe". I want to do the following:

  1. Read the contents of Test.exe into a byte array.
  2. Write the contents of Test.exe (now in a byte array) to a new location (C:\Test.exe).

I am using the following code (found on this site) - but the problem is that "s" always returns a null value. I am using the below code as follows: byte[] b = ReadResource("Test.exe");

public static byte[] ReadResource(string resourceName)
{
    using (Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
    {
        byte[] buffer = new byte[1024];
        using (MemoryStream ms = new MemoryStream())
        {
            while (true)
            {
                int read = s.Read(buffer, 0, buffer.Length);
                if (read <= 0)
                    return ms.ToArray();
                ms.Write(buffer, 0, read);
            }
        }
    }
}  

Hopefully someone can find what I am having trouble seeing.

2 Answers 2

2

You need to specify the full name of the resource. So for example if your application is called Foo:

byte[] b = ReadResource("Foo.Test.exe");

Actually the easiest thing would be to open the assembly with Reflector and look at the exact name of the embedded resource. There might be a namespace in between the name of the application and the name of the resource.

And if you don't have Reflector (yeah it became a paid product), to find out the names of the embedded resources you could use the following code:

foreach (var res in Assembly.GetExecutingAssembly().GetManifestResourceNames())
{
    Console.WriteLine(res);
}

Once you get the exact name of the embedded resource pass it to the ReadResource method.

As yet another alternative you could use ildasm.exe and double click on the MANIFEST which will show you all embedded resources.

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

2 Comments

What is reflector? Is that a 3rd party app?
You can use ILSpy as a free alternative to reflector.
2

You can do this with one line of code if use 'typed' resources.

File.WriteAllBytes("C:\\test1.exe", Resources.TestFile);

To add typed resource:

  • go to project properties Resources tab
  • select File as resource type
  • add your executable file to the resources

    enter image description here

  • now you can reference the file content by Resources.TestFile

5 Comments

That's a great response. Thank you - Just out of curiosity then, why would anybody add an executable file as a resource using any other method if this one is so easy?
@Evan - hmmm... to make life more difficult I guess :)
@Evan - so you've chosen to do it the hard way? :)
Not quite, but he did answer my question that I asked :)
I'm sorry I wasn't helpful :(.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.