Download template from embedded resource

How to load an embedded resource as an ITemplate? The LoadTemplate () method accepts only a string virtual path, and obviously this will not work for embedded resources.

+6
c # embedded-resource
source share
2 answers

Assuming your templates are built-in and should stay that way (which I think you can reconsider), here is a function that I wrote some time ago that I used many times when working with embedded files (mostly .sql files) . It converts the embedded resource to a string. Then you may need to write a template to disk.

public static string GetEmbeddedResourceText(string resourceName, Assembly resourceAssembly) { using (Stream stream = resourceAssembly.GetManifestResourceStream(resourceName)) { int streamLength = (int)stream.Length; byte[] data = new byte[streamLength]; stream.Read(data, 0, streamLength); // lets remove the UTF8 file header if there is one: if ((data[0] == 0xEF) && (data[1] == 0xBB) && (data[2] == 0xBF)) { byte[] scrubbedData = new byte[data.Length - 3]; Array.Copy(data, 3, scrubbedData, 0, scrubbedData.Length); data = scrubbedData; } return System.Text.Encoding.UTF8.GetString(data); } } 

Usage example:

 var text = GetEmbeddedResourceText("Namespace.ResourceFileName.txt", Assembly.GetExecutingAssembly()); 
+2
source share

Your control should look like this:

 public class Con : Control { public Template Content { get; set; } protected override void CreateChildControls() { base.CreateChildControls(); Content = new Template(); // load controls from file and add to this control Content.InstantiateIn(this); } public class Template : ITemplate { public void InstantiateIn(Control container) { // load controls container.Controls.Add((HttpContext.Current.Handler as Page).LoadControl("Emb.ascx")); } } } 

Then the embedded file:

 <%@ Control Language="C#" %> <asp:TextBox ID="Tb" runat="server" /> 

Then, when using the control, it will load the embedded resource, so use:

 <%@ Register Assembly="TestWeb" Namespace="TestWeb" TagPrefix="c" %> <c:Con runat="server" /> 

Creates a TextBox.


If you are trying to access a file inside a DLL, see this implementation of VirtualPathProvider .

0
source share

All Articles