Wednesday, December 3, 2008

Accessing an embedded resource in dll through web URL

Before going to details of refering embedded resource lets discuss what is embedded resource.Its nothing but a file stored or packed inside a dll.So There will be no physical appearence for that file.Hence nobody can access that file through a url which simply points to the folder structure.

Lets see how to embed a resource and get its coresponding URL.
  1. Create a web application.
  2. Add a resource into the project.Resource can be a file of any type.
    1. Right click on the project and click on 'Add existing item'
    2. It will show up a file open dialog.Select the file ,it will be added into your project.
  3. Goto properties of that resource and set build action to 'Embedded Resource'.
  4. Add the attribute for namespace as follows to denote this is a webresource
    [assembly: WebResource("<namespace>.<filename>.<extension>","<mimetype>")]
    Eg :[assembly: WebResource("","image/jpg")]
  5. Now you can refer the resource with the URL returned from the method Page.ClientScript.GetWebResourceUrl(typeof(class name), "<namespace>.<filename>.<extension>");
    Eg:Page.ClientScript.GetWebResourceUrl(typeof(_Default), "WebResourceURLDemo.hello.jpg");

The URL will be pointing to WebResource.axd with some url parameters.These parameters help the system to identify the correct resource.

A sample can be downlaoded from here which stores an image in dll and refering through web resource url.

No comments: