Search code examples
c#stringstring-formatting

string format and single quote


I am using a string format with multiple lines of text and one single quotes is a part of that text. The code is like

     string _query = @"{ts '{0}-{1}-{2} 00:00:00'}
                                 ";
              _query = string.Format(_query, DateTime.Now.Year, DateTime.Now.Month, 25);

But the string format return exception as

  Input string was not in a correct format.

How can we add single quote in a multiline text along with string format


Solution

  • As mentioned in comments, please avoid building query using string, instead use Parameterized SQL queries.

    Regarding your comment on why string Format fails, its because of presence of curly braces in beginning and end of string.You need to escape it. To escape curly braces use "{{" and "}}".

    string _query = @"{{ts '{0}-{1}-{2} 00:00:00'}}";