How to Format Code to Post on your Blog

There is a great web utility available that will format your code so that it is easy to read and looks similar to your IDE syntax highlighting. Best of all, the site is free to use. The utility is provided by manoli.net/csharpformat. Here is the URL:
http://www.manoli.net/csharpformat/

Currently, the site supports formatting of the following languages / code:



  • C#
  • VB.NET
  • HTML
  • XML
  • ASPX
  • T-SQL
  • MSH (code named Monad)

You can use alternating colors on lines to make it easier for your eyes to move through the code and also it will put line numbers in for you if you want.

You can choose to either embed their CSS style sheet in your post or set up your blog template's header section to have their style sheet in it. Then you can post without style information and it will format correctly. Here is a sample of how some C# code looks with the utility:

 

   1:  // shows the message hello world
   2:  public void ShowHelloWorld()
   3:  {
   4:      string sHello = "hello";
   5:      string sWorld = "world";
   6:   
   7:      // concat the strings and show them
   8:      string sHelloWorld = sHello + " " + sWorld;
   9:      MessageBox.Show(sHelloWorld);
  10:  }

 

One thing I don't like about the Manoli.net code formatting though is that when you cut and paste, all the line breaks and formatting is lost! This is really annoying because you either have to spend a lot of time reformatting the code or just retype it in again from the example.

I've found another that doesn't quite format things as nicely but it does allow you to copy and paste and retains all the line breaks and formatting. It is also an online editor that you can use for free. Here is the link:

http://dotnetslackers.com/articles/csharpformat.aspx

To use this, you will need to embed a link to their style sheet on your site to apply the formatting. I made a couple of tweaks to the the C# style sheet to make it look a bit more like how I like the code to look. You can download my css here:

format_code.css

This will format the same code above to look something like this:

// shows the message hello world  
public void ShowHelloWorld()   
{   
    string sHello = "hello";   
    string sWorld = "world";   
    
    // concat the strings and show them   
    string sHelloWorld = sHello + " " + sWorld;   
    MessageBox.Show(sHelloWorld); 
}