Search code examples
c#embedded-resource

How to use & execute resources


In a word my logic on my working project is to make a simple program that launches files out of my source code this could be anything like "setup.exe" but to avoid the case that the file from the folder(which is going to execute) is missing I want to compile it or merge with my program I coded (my program + outer documents together)

I can see in the compiled.exe document in debug folder the 2 of them have been merged together ('cause of the bigger file size when I add the program in resources but i cannot use it properly)

I am trying to launch a file from my resources in this example is 2.bat (batch file) but originally I want an .exe file BUT I found it really complicated as it looks like 20 lines of code that I cannot clearly understand what is going on. If I am forced to do it only via resources please make an example with the following resource location "namespaceNAME.properties.resources.file

I have seen resources examples but it looks like the lest 15 lines of code its should a little bit of crazy to right all these code for every single file I want merge with my main program(Like 15 for the 1 + 15 for the 2nd) If you know somehow another way to complete my wants please don't be afraid If not I am ready to accept the answer "Welcome to programming"

REMEMBER the embedded resources is an executable file no image or .txt

EDIT:

This is what I have done so far :

namespace test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        public class EmbeddedResourceFile : IDisposable
        {
            private readonly string _resourceName;
            private readonly Assembly _callingAssembly;

            public string FilePath { get; private set; }

            public EmbeddedResourceFile(string embeddedResourceName, string targetFilePath)
            {
                _resourceName = embeddedResourceName;
                FilePath = targetFilePath;
                _callingAssembly = Assembly.GetCallingAssembly();
                WriteFileToDisk();
            }

            private void WriteFileToDisk()
            {
                File.Delete(FilePath);
                var stream = _callingAssembly.GetManifestResourceStream(_resourceName);
                if (stream == null)
                {
                    throw new InvalidOperationException(string.Format("Embedded resource not found: {0}", _resourceName));
                }
                var fileStream = new FileStream(FilePath, FileMode.CreateNew);
                for (var i = 0; i < stream.Length; i++)
                {
                    fileStream.WriteByte((byte)stream.ReadByte());
                }
                fileStream.Close();
            }

            public void Dispose()
            {
                File.Delete(FilePath);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {   
            var exe =   
            new EmbeddedResourceFile("test.Properties.Resources.ConsoleApplication",
                Path.Combine(Environment.CurrentDirectory, "cports.exe"));
            Process.Start(exe.FilePath);
        }
    }
}

Of course sth goes wrong but I don't know what
I think i have left many void methods untouched for no reason

I have replaced the last with

private void button1_Click(object sender, EventArgs e)
            {   
                var exe =
                new EmbeddedResourceFile("test.Properties.Resources.ConsoleApplication.exe",
                    Path.Combine(Environment.CurrentDirectory, "ConsoleApplication.exe"));
                Process.Start(exe.FilePath);
            }

but error like http://prntscr.com/6nv1yj appears

See the end of this message for details on invoking 
just-in-time (JIT) debugging instead of this dialog box.

************** Exception Text **************
System.InvalidOperationException: Embedded resource not found: test.Properties.Resources.ConsoleApplication.exe
   at test.Form1.EmbeddedResourceFile.WriteFileToDisk() in c:\Users\WindowsX\Desktop\Programms\MultiPackageInstaller\test\test\Form1.cs:line 50
   at test.Form1.EmbeddedResourceFile..ctor(String embeddedResourceName, String targetFilePath) in c:\Users\WindowsX\Desktop\Programms\MultiPackageInstaller\test\test\Form1.cs:line 41
   at test.Form1.button1_Click(Object sender, EventArgs e) in c:\Users\WindowsX\Desktop\Programms\MultiPackageInstaller\test\test\Form1.cs:line 68
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)


************** Loaded Assemblies **************
mscorlib
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.34209 built by: FX452RTMGDR
    CodeBase: file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll
----------------------------------------
test
    Assembly Version: 1.0.0.0
    Win32 Version: 1.0.0.0
    CodeBase: file:///C:/Users/WindowsX/Desktop/Programms/MultiPackageInstaller/test/test/bin/Debug/test.exe
----------------------------------------
System.Windows.Forms
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.34209 built by: FX452RTMGDR
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
System.Drawing
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.34209 built by: FX452RTMGDR
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Drawing/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
----------------------------------------
System
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.34209 built by: FX452RTMGDR
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System/v4.0_4.0.0.0__b77a5c561934e089/System.dll
----------------------------------------
System.Configuration
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.34209 built by: FX452RTMGDR
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Configuration/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll
----------------------------------------
System.Xml
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.34209 built by: FX452RTMGDR
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Xml/v4.0_4.0.0.0__b77a5c561934e089/System.Xml.dll
----------------------------------------

************** JIT Debugging **************
To enable just-in-time (JIT) debugging, the .config file for this
application or computer (machine.config) must have the
jitDebugging value set in the system.windows.forms section.
The application must also be compiled with debugging
enabled.

For example:



<configuration>
    <system.windows.forms jitDebugging="true" />
</configuration>

When JIT debugging is enabled, any unhandled exception
will be sent to the JIT debugger registered on the computer
rather than be handled by this dialog box.

How is even possible not to be found I have clicked on my test project > properties > resources > add resource and opened the file

http://prntscr.com/6nv4ki

                            ****READ 'TILL THE END****

Solution

  • I wrote a simple EmbeddedResourceFile persistence object for doing things like this.

    This will work for included files whose properties are set to Build Action -> Embedded Resource

    using System;
    using System.IO;
    using System.Reflection;
    
    namespace EmbeddedResourceLauncherDemo
    {
        public class EmbeddedResourceFile : IDisposable
        {
            private readonly string _resourceName;
            private readonly Assembly _callingAssembly;
    
            public string FilePath { get; private set; }
    
            public EmbeddedResourceFile(string embeddedResourceName, string targetFilePath)
            {
                _resourceName = embeddedResourceName;
                FilePath = targetFilePath;
                _callingAssembly = Assembly.GetCallingAssembly();
                WriteFileToDisk();
            }
    
            private void WriteFileToDisk()
            {
                File.Delete(FilePath);
                var stream = _callingAssembly.GetManifestResourceStream(_resourceName);
                if (stream == null)
                {
                    throw new InvalidOperationException(string.Format("Embedded resource not found: {0}", _resourceName));
                }
                var fileStream = new FileStream(FilePath, FileMode.CreateNew);
                for (var i = 0; i < stream.Length; i++)
                {
                    fileStream.WriteByte((byte)stream.ReadByte());
                }
                fileStream.Close();
            }
    
            public void Dispose()
            {
                File.Delete(FilePath);
            }
        }
    }
    

    Then you can execute something by calling this. Be sure to figure out your own strategy for cleaning up any persisted files.

        [TestMethod]
        public void EmbeddedResourceFile_LaunchEmbeddedProgram()
        {
            var exe = 
                new EmbeddedResourceFile("EmbeddedResourceLauncherDemo.ResourceApp.cports.exe", 
                    Path.Combine(Environment.CurrentDirectory, "cports.exe"));
            Process.Start(exe.FilePath);
        }