Load template from embedded resource

后端 未结 2 773
清歌不尽
清歌不尽 2021-02-16 00:03

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.

2条回答
  •  爱一瞬间的悲伤
    2021-02-16 00:23

    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);
       }
    }
    

    Example usage:

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

提交回复
热议问题