Using Embedded Images in ASP.Net

I have been working on an asp.net application where I want to use a treeview which is calling for quite a number of images and I didn't want to worry about copying all the images with my assembly, so I embedded the images into my assembly.  But I could not figure out any way to directly output the images so I wrote another aspx file that will display the image. 
<%@ Page Language="C#" %>
<%
  string image = string.Empty;
  string asmName = string.Empty;
  
  try
  {
    Response.Clear();

    // Get Image Name from request
    image = Request["img"].Replace("/"".");   
    
    // Get Assembly Name from request
    asmName = Request["asm"];

    // Default the Assembly Name to the current assembly
    if(asmName == null || asmName == string.Empty)
      asmName = this.GetType().Assembly.FullName;

    // Load the Assembly
    System.Reflection.Assembly asm = System.Reflection.Assembly.Load(asmName);
    
    // Get the Image stream from the embedded image
    System.IO.Stream stream = asm.GetManifestResourceStream(image);
    
    // Create an Image object from the stream
    System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
    
    // Save the Image stream to the output stream
    img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
  }
  catch(Exception ex)
  {
    Response.Write("Exception: <BR>image = " + image + 
      "<BR>asmName = " + asmName + "<BR>" + 
      ex.Message + "<BR>" + ex.StackTrace.Replace("\n""<BR>"));  
  }
  finally
  {     
    Response.End(); 
  }
%>


This seems to work pretty well. Here is an example of how to use it
<IMG src="image.aspx?asm=<AssemblyName>&img=<namespace>.testimage.gif" />

This will prevent me from having to copy all the images; all I would need to copy is the Assembly and the image.aspx file.  What do you guys think?  Does anyone see any potential problems with this?

1 Comment

  • Luckily System.Reflection.Assembly.Load(asmName) doesn't allow asmName to be a url, in which case I could load like a 1GB assembly into your memory space. In general I don't like it when the end user can derive anything from my urls about my system (other than the fact that I'm using aspx).

Comments have been disabled for this content.