Trouble with Single Quotes and String.Replace()

by Marvin 1. September 2008 15:05

I've used String.Replace() before and never had a problem.  Tonight, however, I needed to replace a single quote in a string with a backslash followed by a single-quote.  Seemed like a fairly simple task, but for some reason, my string looked exactly the same after applying String.Replace.  It took me an hour of searching the internet to find a solution.    Perhaps the most frustrating part was finding two places on www.experts-exchange.com that claimed to have a solution to the problem which I could see if I just signed up for their paid subscription to the site.  Blech! 

So, here was my broken code:

    public string escapeChar(string strToEsc)
    {
        if (strToEsc.IndexOf("'") > -1)
        {           
            strToEsc = strToEsc.Replace("'", "\'"); // note: that's doublequote singlequote doublequote comma doublequote backslash singlequote doublequote

        }
        return strToEsc;
    }

You might wonder why I am doing this.  Or, you may know why I am doing it and you are shaking your head.  Ok, so this is bad practice.  I am taking a string and escaping out single quotes before sending it as a sql statement to a database.  From a security standpoint, it's bad practice to build sql statements like this:

sql = "select column from table where column = " + someVariable;

Instead, I should be using parameters.  But, I am not, so sue me.  Just please, don't try to execute any sql injection attacks against my databases.  Tongue out

So, I am using a MySQL database behind the web application I am working on.  MySQL uses single-quotes to surround values in a where clause (ie. where `column` = 'value') and backslashes to escape characters.  Consequently, if someone typed an apostrophe in my text field and submitted the form, my page would crash with an error from the database.  This function was intended to fix that.

So, how did I get it working.  Well, after a bunch of googling, here's the solution I found that worked for me:

    public string escapeChar(string strToEsc)
    {
        if (strToEsc.IndexOf("'") > -1)
        {           
            strToEsc = strToEsc.Replace("'", @"\'"); // notice the addition of the @ symbol
        }
        return strToEsc;
   

The @ symbol was the secret.  The problem was that C# normally interprets a backslash in a string as preceding some kind of special character (ie. /n for newline).  The @ in front of the string tells the C# compiler not to interpret a backslash as preceding a special character as it ususually would but rather to treat it "as-is".  In this instance, if I say "backslash singlequote", I mean "backslash singlequote".  And, actually, in this case, the compiler turned \' into \\'.  That threw me for just a second, but I recognized the intent from my javascript background.  Since a backslash normally precedes a special character, the way to render an actual backslash in javascript is to use two backslashes.  Apparently, C# does the same thing. 

Currently rated 4.7 by 6 people

  • Currently 4.666667/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

Web Development

Comments

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading



About the author

I am a junior-level C# .NET developer living in Nashville, TN.  I'm currently working in biomedical informatics, developing a web service, a MySql database, and a web application.  Every week or so, I spend hours trying to figure out how to do something, and after I find the solution, I really want to make sure I don't go through that exercise again.  I love to write.  It helps me to remember things.  So, I use this blog as a way to document those painful lessons as I learn them.  It has already helped me to be able to refer back to them.  I hope some of these will save someone else some time as well.