Bitterblue
Bitterblue

Reputation: 14075

C# - Add File as Resource to my Exe at Runtime

I discovered that I can add Files (*.jpg) to my C# Resources in Visual Studio 2010. As far as I could read it should be possible to re-assemble the exe at runtime. I don't want to strip the exe apart by myself. I'm looking for C# routines that do that for me. Of course I don't want to modify the running exe but a copy of it. I could also live with it putting my source code inside my exe if I need to compile it again at runtime.

My goal:

  1. Create copy of the running exe
  2. Add a file to that copy somehow.
  3. Close the running app
  4. When user executes the copy it must have the file as resource inside. That's it.

Edit: C# compiler + Visual Studio 2010 is available at target system.


(I'm not programming a full installer, please don't say those bad words: "re-inventing" and "wheel", I know them by myself)

Upvotes: 4

Views: 3372

Answers (1)

PhonicUK
PhonicUK

Reputation: 13864

You'd have a very hard time modifying your resource section in a way that won't break your executable without the benefit of a full compiler.

What you can do instead however is:

  • Make a ZIP file (or other archive that contains all your files)
  • Do a dumb-append of the contents of your ZIP file to the end of the executable
  • Also append an int32 containing the length of your archive

You can read it by opening a FileStream for your own executable starting at ExecutableLength - ZipLength - 4 and reading ZipLength bytes - which gives you just the zip portion which can be read using DotNetZip or another library.

Then when you want to modify the stored data:

  • Rename your existing executable while running (which you can do)
  • Read the first ExecutableLength - ZipLength - 4 bytes of your executable and write them to a new file with the name your executable had originally before it was renamed.
  • Create the new ZIP archive with your information in and append that.
  • Append the int32 of the length of your new archive.
  • Close the existing app and launch the new one.

Tadah - an executable that can modify its own stored resources.

Upvotes: 2

Related Questions