I have a C# program that needs to process data and store it in SQL Server. The issue I am having is that some of the data being saved legitimately contains a single quote. When saving the data I need to locate the items that have single quotes in them and actively replace the single quote with two single quotes together so that I don't get a truncated string.
At present whereever I am adding data that might contain a single quote I am passing it through the following routine which I have in a static module called FSQ (Fix Single Quote), this is the routine:
/// <summary>
/// Fix Single Quote - Used to remove Double quotes from strings that would confuse Access database by replacing with Single Quotes.
/// </summary>
/// <param name="s">String text to be fixed by removing double quotes.</param>
/// <returns>The original string with any double-quotes removed and replaced with single quotes. If an error occurs will return an empty string.</returns>
public static string FSQ(string s)
{
string tmp ="";
try
{
if (s == null)
return "";
s = s.Trim();
if (s == "")
return s;
if(s.Contains("'"))
{
if(!s.Contains("''"))//Already been fixed previously so skip here
tmp = s.Replace("'", "''");
s = tmp;
}
return s;
}
catch (Exception ex)
{
PEH("FDQ", "Common Module", ex.Message);
return "";
}
} //public static String FDQ(String s)
This works and my strings get saved OK to SQL but because there are a lot of calls to this routine, the performance sucks as the program loops through thousands of rows of data whilst it's processing.
Is there a more efficient routine that would negate the need to call this function? Mostly I am just building update or insert queries that contain these items.
Any help appreciated.