从嵌入式资源加载模板

Mad*_*unk 6 c# asp.net itemplate embedded-resource

如何将嵌入资源作为ITemplate加载?LoadTemplate()方法只接受字符串虚拟路径,显然这对嵌入式资源不起作用.

Rus*_*ure 2

假设您的模板是嵌入的并且需要保持这种方式(我认为您可能需要重新考虑),这是我不久前编写的一个函数,在处理嵌入文件(主要是 .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);
   }
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

var text = GetEmbeddedResourceText("Namespace.ResourceFileName.txt",
                                   Assembly.GetExecutingAssembly());
Run Code Online (Sandbox Code Playgroud)