Serving embedded resources with WebResource.axd

by timvasil 11/26/2007 1:56:00 PM

If you need to build a URL to an embedded resource and don't have a reference to the Page object to call ClientScript.GetWebResourceUrl, you can use the following:

private static readonly MethodInfo _getWebResourceUrlMethod =
    typeof(ClientScriptManager).GetMethod(
        "GetWebResourceUrl",
        BindingFlags.NonPublic | BindingFlags.Static,
        null,
        new Type[] { typeof(Page), typeof(Type), typeof(string), typeof(bool) }, null);

        /// <summary>
        /// Provides a URL to an embedded resource.
        /// The resource is served with .NET's built in WebResource.axd handler.
        /// You <b>must</b> supply an <c>[assembly: WebResource(resourcePath, mimeType)]
        /// attribute for each resource to be served in this manner.</c>
        /// </summary>
        /// <param name="url">Location of the resource, e.g.
        /// <c>assembly://Assembly.Name/Assembly.Name.Folder1.Folder2/Resource.txt</c>.
        /// The hostname portion specifies the assemby name, and the path specifies the
        /// namespace name and resource name of the resource.</param>
        /// <returns>The external URL to access the embedded resource</returns>
        public static string GetEmbeddedResourceUrl(Uri url)
        {
            if (url == null)
            {
                throw new ArgumentNullException();
            }
            if (url.Scheme != "assembly")
            {
                throw new ArgumentException("Supplied URI must use 'assembly' scheme");
            }
            string assemblyName = url.Host;
            string resourcePath = url.AbsolutePath.Substring(1).Replace('/', '.');
            Assembly resourceAssembly = Assembly.Load(assemblyName);
            return (string)_getWebResourceUrlMethod.Invoke(null,
                   new object[] { null, resourceAssembly.GetTypes()[0], resourcePath, false });
        }

Tags:

ASP.NET | .NET Framework

Comments are closed

Search

Calendar

«  February 2012  »
SuMoTuWeThFrSa
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910

View posts in large calendar

Recent comments

Archive