Search code examples
c#winformsdllembedded-resourcesystem.reflection

Working with embedded resources in external dll, without visual studios


Okay, so I've ran into a problem that I am having trouble finding a solution. There are plenty of solutions using visual studios properties. The issue is that I'm not using visual studios, I'm using csc.exe to compile my code.

Here's what I have so far.


exe.cmd

dll.cmd

Resource.dll

Main.csx

Rsc.csx

a.png


This is all of the code for the .cmd files and .csx files

exe.cmd

@echo off
csc.exe /target:winexe /reference:Resource.dll /out:Main.exe Main.csx
pause

dll.cmd

@echo off
csc.exe /target:library /resource:a.png /out:Resource.dll Rsc.csx
pause

Rsc.csx

using System;
using System.IO;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;

namespace EmIm
{
    public static class Bck
    {
        public static Image GetBck()
        {
            Bitmap bmp = new Bitmap(Assembly.GetExecutingAssembly().GetManifestResourceStream("a.png"));
            Image rtn = bmp;
            return rtn;
        }
    }
}

Main.csx

using System;
using System.IO;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;

using EmIm;

namespace prg
{
    class class_m
    {
        public static void Main()
        {
            Form f1 = new Form();
            try
            {
                f1.BackgroundImage = Bck.GetBck();
            }
            catch(Exception e)
            {
                MessageBox.Show(e.Message);
            }
            f1.ShowDialog();
        }
    }
}

When I run this, I get a messagebox that displays value of 'null' is not valid for 'stream'

What steps do I need to take to be able to access a.png with reflection, I have checked to make sure a.png is the correct name in the assembly. Any help would be greatly appreciated. Thanks :)


Solution

  • A large thanks to Hans Passant for providing the simple solution to this problem. I had no idea even where to look to find out how to answer this problem, but he summed it up in a single comment.

    only one file had to be altered in order for the program to work

    new Rsc.csx file

    using System;
    using System.IO;
    using System.Drawing;
    using System.Reflection;
    using System.Windows.Forms;
    using System.Runtime.CompilerServices;
    
    namespace EmIm
    {
        public static class Bck
        {
            [MethodImpl(MethodImplOptions.NoInlining)]
            public static Image GetBck()
            {
                Bitmap bmp = new Bitmap(Assembly.GetExecutingAssembly().GetManifestResourceStream("a.png"));
                Image rtn = bmp;
                return rtn;
            }
        }
    }
    

    Once again, thanks Hans Passant for that quick fix to my problem, hopefully any other programmers stubborn enough to avoid Visual Studios could possibly look to this to find a solution that works without it. Have fun programming :)