Thursday, November 13, 2008

Build StringBuilder Code from C#

With a little quick and dirty code, you can generate StringBuilder code from C# code. To use it, all you need is a WinForms project with two TextBoxes and a Button. This is very useful for creating code generation tools. My reason is that I am in the process of creating a dynamic form generation tool for SharePoint Lists and Document Libraries.

Form Example Screenshot:

C# Code (Not Optimized):

public string GetStringBuilderCodeFromCSharp(string[] lines)
    StringBuilder stringBuilder = new StringBuilder();
    string line = string.Empty;
    foreach (string s in lines)
        line = s.Replace("    ", "\\t").TrimEnd();    //Replace four spaces with tabs. VS cs uses spaces
        if (line.StartsWith("\\t\\t"))                      //Eliminate double tabs. VS cs defaults with tab
            line = line.Substring(4, line.Length - 4);
        line = line.Replace("\"", "\\\"");               //Replace double quotes with escaped double quotes
        line = "stringBuilder.Append(\"" + line + "\\r\\n\");\r\n";   //StringBuilder Append Code
    stringBuilder.Insert(0, "StringBuilder stringBuilder = new StringBuilder();\r\n");
    return stringBuilder.ToString();