Monday, October 26, 2009

Include literal file contents in ASP.NET

I was looking for something similar to Velocity's #include for ASP.NET. <% Response.WriteFile([filename]); %> works well, but a .NET control for this could be nice. Here is my attempt (MIT license):

using System.IO;
using System.Web;
using System.Web.UI;

namespace FooControls
{
  public class LiteralContentFromFile : Control
  {
    public string Path { get; set; }

    protected override void Render(HtmlTextWriter writer)
    {
      var server = HttpContext.Current.Server;
      var physicalPath = server.MapPath(Path);
      var fileContents = File.ReadAllText(physicalPath);
      writer.Write(fileContents);
    }
  }
}

Usage in an .aspx file (WebForms or ASP.NET MVC):

<%@ Register TagPrefix="foo"
  Namespace="FooControls" Assembly="FooControls" %>
...
<foo:LiteralContentFromFile runat="server"
  Path="~/path/to/file" />

Edit: subclassing System.Web.UI.Control instead of System.Web.UI.WebControls.WebControl which added unnecessary and unwanted behavior (for example, wrapped the output with <span>).