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?
-
\$\begingroup\$ Did you have a look at the answers to this question: stackoverflow.com/questions/14480724/… \$\endgroup\$Graipher– Graipher2017年05月17日 11:38:31 +00:00Commented May 17, 2017 at 11:38
2 Answers 2
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);
-
\$\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\$Igor Soloydenko– Igor Soloydenko2017年05月20日 02:35:49 +00:00Commented May 20, 2017 at 2:35
You have two options really:
- 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 - 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.