using System; using System.Collections.Generic; using System.IO; using System.Text; namespace ln.templates.html { public class FileSystemTemplateSource : ITemplateSource { public String BasePath { get; } Dictionary templateDocuments = new Dictionary(); public FileSystemTemplateSource(String path) { if (!Directory.Exists(path)) throw new FileNotFoundException(); BasePath = path; } public TemplateDocument GetTemplateByPath(string path) { string templatePath = Path.Combine(BasePath, path); if (!File.Exists(templatePath)) { if (templateDocuments.ContainsKey(path)) templateDocuments.Remove(path); throw new FileNotFoundException(); } if (!templateDocuments.TryGetValue(path,out TemplateDocument templateDocument)) { templateDocument = ReadTemplateDocument(path); templateDocuments[path] = templateDocument; } else { DateTime templateDateTime = File.GetLastWriteTime(templatePath); if (templateDateTime.Ticks != templateDocument.TemplateVersion) { templateDocument = ReadTemplateDocument(path); templateDocuments[path] = templateDocument; } } return templateDocument; } TemplateDocument ReadTemplateDocument(string path) { string templatePath = Path.Combine(BasePath, path); TemplateReader templateReader = new TemplateReader(); using (StreamReader sr = new StreamReader(templatePath)) { templateReader.Read(sr); } templateReader.TemplateDocument.TemplateVersion = File.GetLastWriteTime(templatePath).Ticks; return templateReader.TemplateDocument; } } }