using System; using System.Collections.Generic; using System.IO; using System.Net; namespace AllocsFixes.NetConnections.Servers.Web { public class StaticHandler : PathHandler { private string datapath; private string staticPart; private bool cache; private Dictionary fileCache = new Dictionary (); public StaticHandler (string staticPart, string filePath, bool cache) { this.staticPart = staticPart; this.datapath = filePath; this.cache = cache; } public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp) { try { string fn = req.Url.AbsolutePath.Remove (0, staticPart.Length); byte[] content; if (cache) { if (!fileCache.ContainsKey (fn)) { if (!File.Exists (datapath + "/" + fn)) { resp.StatusCode = (int)HttpStatusCode.NotFound; return; } fileCache.Add (fn, File.ReadAllBytes (datapath + "/" + fn)); } content = fileCache [fn]; } else { if (!File.Exists (datapath + "/" + fn)) { resp.StatusCode = (int)HttpStatusCode.NotFound; return; } content = File.ReadAllBytes (datapath + "/" + fn); } resp.ContentType = MimeType.GetMimeType (Path.GetExtension (fn)); resp.ContentLength64 = content.Length; resp.OutputStream.Write (content, 0, content.Length); } catch (Exception e) { Log.Out ("Error in StaticHandler.HandleRequest: " + e); } } } }