Listing Code on your Webpage

May 18th, 2010Posted by Steve

 

Web How many times have you seen those weird little text boxes on a web site to display code complete with the scroll bar but only two lines long, impossible to navigate or copy the code, virtually defeating the purpose of publishing them in the first place. How do you display code on a web page anyway? It's surprising simple, it just needs a little bit of thought, what I wanted was something a little neater. I also wanted all of this code to be dynamic and read from a file or database and formatted correctly all automatically for any type of code be it XML, c# or vb.

The first thing I did was to create a webcontrol in Visual Studio. On this web control I added the following;


<%@ Control Language="C#" AutoEventWireup="true" CodeFile="PageCode.ascx.cs" Inherits="PageCode" %>
<p id="code" runat="server">
</p>

Now going to the code behind I then added a short piece of code to read and format the file. Note that a property has been added which is accessible from the page making it easier to use. The text is html encoded and all of the spaces and carriage returns are replaced by their html encoded equivalents.

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

public partial class PageCode : UserControl
{
    /// <summary>
    /// Property accessible from the page
    /// </summary>
    public string Source
    { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        string src = string.Format("MyCode/{0}", this.Source);
        using (TextReader reader = new StreamReader(Server.MapPath(src)))
        {
            string snippet = reader.ReadToEnd();
            snippet = Server.HtmlEncode(snippet).Replace("\r\n", "<br>").Replace(" ","&nbsp;");
            code.InnerHtml = string.Format("<pre><code>{0}</code></pre>", snippet);
            reader.Close();
        }
    }
}


Using It:

<uc2:PageCode ID="PageCode1" Source="mycodefile.txt" runat="server" />

Thats about it, I added an entry to the stylesheet so it wraps correctly and is the right colors and I was good to go.