Escaping Single Quotes in Input for C# WinForms

To properly replace apostrophes in C# and SQL Server 2019, one should not use the method of apostrophe replacement as it is not the correct approach. Instead, using the code below is recommended for entering and selecting data. For example, to insert data into a table or to read data from a table, this method should be used. This approach is the correct way to insert apostrophes in C# and SQL Server.


Solution 1:

Perform this action to avoid the need for mental effort.

s = s.Replace("'", @"'");


Solution 2:


If this is related to MVC.NET (MVC5+), here’s an alternative solution that could be considered.

var data= JSON.parse('@Html.Raw(HttpUtility.JavaScriptStringEncode(JsonConvert.SerializeObject(Model.memberObj)))');

By utilizing this feature, you can effectively evade and transmit information to views through JavaScript. The crucial aspect is:

HttpUtility.JavaScriptStringEncode


Solution 3:


Here’s a function I’ve written that can quickly and easily escape text for use in a MySQL insert clause.

    public static string MySqlEscape(Object usString)
    {
        if (usString is DBNull)
        {
            return "";
        }
        else
        {
            string sample = Convert.ToString(usString);
            return Regex.Replace(sample, @"[rnx00x1a\'""]", @"$0");
        }
    }

Frequently Asked Questions

Posted in Uncategorized