[英]Load template from embedded resource
如何將嵌入資源作為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" />
將創建一個TextBox。
如果您嘗試訪問DLL中的文件, 請參閱VirtualPathProvider的此實現 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.