如何将嵌入式资源作为ITemplate加载?LoadTemplate()方法只接受字符串虚拟路径,显然这对于嵌入式资源无效。
如何将嵌入式资源作为ITemplate加载?LoadTemplate()方法只接受字符串虚拟路径,显然这对于嵌入式资源无效。
假设您的模板是嵌入式的并且需要保持这种方式(我认为您可能要重新考虑),这里是我写的一个函数,我在处理嵌入式文件时(主要是 .sql 文件)已经成功使用多次。它将嵌入资源转换为字符串。然后,您可能需要将模板写到磁盘上。
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);
}
}
使用示例:
var text = GetEmbeddedResourceText("Namespace.ResourceFileName.txt",
Assembly.GetExecutingAssembly());
你的控件应该长成这样:
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"));
}
}
}
然后是嵌入的文件:
<%@ Control Language="C#" %>
<asp:TextBox ID="Tb" runat="server" />
然后,在使用控件时,它会加载嵌入的资源,因此使用:
<%@ Register Assembly="TestWeb" Namespace="TestWeb" TagPrefix="c" %>
<c:Con runat="server" />
将创建一个文本框。
如果您正在尝试访问 DLL 文件中的文件,请查看 VirtualPathProvider 的实现。
ITemplate
是从哪里来的吗? - JaredPar