Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from an assembly with embedded resources

I built an assembly containing one js file. I marked the file as Embedded Resource and added it into AssemblyInfo file.

I can't refernce the Assembly from a web site. It is in the bin folder but I don't see the reference to it.

It seems like not having at least a class inside the assembly I can't reference it.

I would include the js file into my pages from the assembly.

How should I do this?

Thanks

like image 389
opaera Avatar asked Oct 15 '22 00:10

opaera


1 Answers

I do exactly the same thing in one of my projects. I have a central ScriptManager class that actually caches the scripts as it pulls them, but the core of extracting the script file from the embedded resource looks like this:

internal static class ScriptManager
{
    private static Dictionary<string, string> m_scriptCache = 
                                     new Dictionary<string, string>();

    public static string GetScript(string scriptName)
    {
        return GetScript(scriptName, true);
    }

    public static string GetScript(string scriptName, bool encloseInCdata)
    {
        StringBuilder script = new StringBuilder("\r\n");

        if (encloseInCdata)
        {
            script.Append("//<![CDATA[\r\n");

        }

        if (!m_scriptCache.ContainsKey(scriptName))
        {
            var asm = Assembly.GetExecutingAssembly();

            var stream = asm.GetManifestResourceStream(scriptName);

            if (stream == null)
            {
                var names = asm.GetManifestResourceNames();
                // NOTE: you passed in an invalid name.  
                // Use the above line to determine what tyhe name should be
                // most common is not setting the script file to be an embedded resource
                if (Debugger.IsAttached) Debugger.Break();

                return string.Empty;
            }

            using (var reader = new StreamReader(stream))
            {
                var text = reader.ReadToEnd();

                m_scriptCache.Add(scriptName, text);
            }
        }

        script.Append(m_scriptCache[scriptName]);

        if (encloseInCdata)
        {
            script.Append("//]]>\r\n");
        }

        return script.ToString();
    }
}

EDIT

To provide more clarity, I've posted my ScriptManager class. To extract a script file, I simply call it like this:

var script = ScriptManager.GetScript("Fully.Qualified.Script.js");

The name you pass in it the full, case-sensitive resource name (the exception handler gets a list of them by calling GetManifestResourceNames()).

This gives you the script as a string - you can then put it out into a file, inject it into the page (which is what I'm doing) or whatever you like.

like image 132
ctacke Avatar answered Oct 18 '22 13:10

ctacke