从嵌入的资源加载模板 [英] Load template from embedded resource

查看:191
本文介绍了从嵌入的资源加载模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何可以加载嵌入资源作为了Itemplate?该LoadTemplate()方法只接受一个字符串虚拟路径,显然这不会对嵌入式资源工作。

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

推荐答案

假设你的模板嵌入,需要保持这种方式(我想你可能要重新考虑),这里是我写了一段时间后,一个功能我已经嵌入文件(主要是.sql文件)打交道时成功使用了很多次。它把一个嵌入资源的字符串。那么你可能需要编写模板到磁盘。

Assuming that your templates are embedded and need to stay that way (which I think you may want to reconsider), here is a function I wrote a while back that I've used successfully many times when dealing with embedded files (mostly .sql files). It converts an embedded resource to a string. You may then need to write your template out 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);
   }
}

实例:

var text = GetEmbeddedResourceText("Namespace.ResourceFileName.txt",
                                   Assembly.GetExecutingAssembly());

这篇关于从嵌入的资源加载模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆