11

Main Question:
Is there a way to insert ONE double quotation in a string in C#

Information:
I am trying to perform something like the following SQL Select statement in C#

SELECT Name FROM Production.Product
WHERE CONTAINS(Name, '"chain*"');  

I interpreted it this as follows:

string selectCommand= @"select Name from Production.Products  
WHERE contains (Name,'\"" + chain+ "*\"')");

But I'm getting the string back as:

" WHERE contains (Name,'"chain"')"

I've also tried the way in this SOF question but it didn't work either!:

string selectCommand= @"select Name from Production.Products  
where contains (doc.document_name,'"""""" + full + """"""')");
Gerhard
  • 6,850
  • 8
  • 51
  • 81
Majd
  • 1,358
  • 3
  • 15
  • 29
  • 2
    You should consider using SQL parameters instead of building the query by concatenation. Makes life easy and more secure. – Johann Blais Feb 25 '11 at 06:19

5 Answers5

8

If you look at the documentation for string literals you will find that there are two formats. The regular format where you have to escape all teh following characters:

', ", \, 0, a, b, f, n, r, t, u, U, x, v.

So your string should be written as follows:

string query = "WHERE CONTAINS(Name, \'\"chain*\"\');";

or verbatim literals, which are preceded with an 'at' symbol, where you only escape double quotes by 'doubling up':

string query = @"WHERE CONTAINS(Name, '""chain*""');";

So just drop the '@' from your string and it will work.

ColinE
  • 68,894
  • 15
  • 164
  • 232
  • in my case "chain" is a variable and that was the source of the problem .. but ur answer was very useful! .. issue solved! :-) – Majd Feb 25 '11 at 06:52
7

Its because you have a @ at the start of your string

string selectCommand= "select Name from Production.Products where contains (doc.document_name,\'\"" + full + "*\"\');";

You basically need to escape the ' and "

Jason Jong
  • 4,310
  • 2
  • 25
  • 33
2

Simply drop the @ at the beginning of your string and it should work.

The reason why the backslash is preserved in your string is because you've told the string not to replace escaped character sequences by placing the @ in front of the string. Removing the @ will allow your escaped characters to be, well, escaped.

rein
  • 32,967
  • 23
  • 82
  • 106
0

Something like this maybe:

string full = "abc";
string selectCommand= @"select Name from Production.Products where contains (doc.document_name,'""" + full + "*\"')";
Sascha
  • 10,231
  • 4
  • 41
  • 65
0

The "@" won't help you here. Remove it, and you should be fine. This should work:

Console.WriteLine("...(doc.document_name,'\"" + full + "*\"')");

If you really want to keep the "@", try this:

Console.WriteLine(@"...(doc.document_name,'""" + full + "*\"')");

silverbeak
  • 312
  • 3
  • 12