从嵌入式资源加载模板

如何将嵌入资源作为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#" %>  

然后在使用控件时,它将加载嵌入的资源,因此使用:

 <%@ Register Assembly="TestWeb" Namespace="TestWeb" TagPrefix="c" %>  

将创建一个TextBox。


如果您尝试访问DLL中的文件, 请参阅VirtualPathProvider的此实现 。