The way I have done this before is as follows:
- Use IndexOf to get the index of the first occurrence of the character.
- Get a substring of the original string starting at the index found in Step 1
- Reverse the substring found in Step 2
- Repeat Step 1 on the reversed string from Step 3, and you are now left with a substring containing the string from after the first ' character to before the last one.
- Reverse the substring from Step 4 again (to get it back to original order) and replace the remaining ' characters with \'
Rebuild the string using (pseudoCode) -
finalString = string.Concat(
originalString.Substring(0, firstIndex),
replacedSubstringFromStep5,
originalString.Substring(secondIndex, originalStringLength - 1)
This will get you a string with anything before and including the first ' character and anything after the last one from the original string, and everything in between will be the replaced ' characters that are now escaped for your MySQL query.
Hope this helps!
Edit: note when I did this, it was for string manipulation in an interlinking application, and not for database queries. I do agree it is better to use stored procs and parameters as others have stated; however, the solution I have provided, without getting into best practices and such, will do what OP is seeking.
.IndexOf(int, int). So what have you tried?