Passing a string, around quotation marks into another string, all in a mutli line string

Posted on

Problem

the title might sound confusing but i have a multi line string which is my source code to be compiled. Inside that string i have a messagebox that will display another string, inside that string i want to pass a string. It got very confusing with all the quotation marks but i finally got it working:

        string source = @"
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Threading.Tasks;
        using System.Windows.Forms;

        namespace Compiler
            {
                static class Program
                {
                    static void Main()
                    {
                        MessageBox.Show(""this is my message: "" + """ + txtMessage.Text + @"""" + @");
                    }
                }
            }";

This returns: MessageBox.Show(“this is my message: ” + “Hello”); providing the value in txtMessage = Hello

So this works but is very messy, also if i pass something like “hi, into txtMessage that will mess it up because of the quotation mark, kinda like a sql injection. Would there be a better way to do this?

Solution

No matter how you do it, it’ll be always messy. Instead of hardcoding the strings use resource files instead. You can embed *.txt files inside the exe/dll and easily read them without having to escape anything.

See this question on Stack Overflow: How to read embedded resource text file
. You’ll find everything you need there.

To insert the message use the {0} placeholder with

string.Format(stringFromResource, txtMessage.Text);

You have two options really:

  1. Add arguments to Main so the string can be passed when you run the compiled program; i.e. don’t put the string into the source
  2. Perform your own escaping on the string you’re putting into the source code

E.g. for number 2 at the least you’ll have to escape " to " and escape any which is not part of an escape sequence (or just always escape it).

Leave a Reply

Your email address will not be published. Required fields are marked *