1
\$\begingroup\$

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?

asked May 17, 2017 at 10:44
\$\endgroup\$
1

2 Answers 2

3
\$\begingroup\$

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);
answered May 19, 2017 at 21:58
\$\endgroup\$
1
  • \$\begingroup\$ +1 This is a good approach. a) Things indeed are not messy this way. b) There is clear separation of concerns -- real code is apart from data. \$\endgroup\$ Commented May 20, 2017 at 2:35
0
\$\begingroup\$

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).

string SanitizeString(string input)
{
 if (input == null)
 {
 // throw or return string.Empty
 }
 // Your logic to make the string safe here
}

I'd be worried about getting number 2 right so I'd be more likely to go for option 1.

answered May 17, 2017 at 11:23
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.