Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
For a sql string to be sent in C# I need to convert ' character inside the inside the string to " character.

What I have tried:

I tried to replace the characters in C# but I couldn't.
Posted
Updated 26-Jan-17 3:00am

str = str.Replace("'", "\"");
 
Share this answer
 
Comments
Richard Deeming 26-Jan-17 9:02am    
That answers the immediate question, but doesn't solve the SQL Injection vulnerability that the OP is creating. :)
#realJSOP 26-Jan-17 9:12am    
I'm all about instant gratification.
bahman01 26-Jan-17 9:26am    
I know about sql injection. I want to use in some cases for formatting string.
Jochen Arndt 26-Jan-17 9:07am    
There is also a method that replaces characters:
str = str.Replace('\'', '"');
bahman01 26-Jan-17 9:28am    
Thank you so much!
Quote:
For a sql string to be sent in C# I need to convert ' character inside the inside the string to " character.

No, you don't.

Based on the description, you're trying to "escape" special characters in a SQL query, because you're using string concatenation to add parameters to the query. But that leaves your code vulnerable to SQL Injection[^].

Instead, you need to use a parameterized query. That way, you don't need to worry about "special" characters, and you can just submit the values unchanged.

For example:
C#
string theName = "Seamus O'Leary";

using (var connection = new SqlConnection("..."))
using (var command = new SqlCommand("SELECT SomeColumns FROM YourTable WHERE SomeName = @Name And SomeDate >= @MinDate", connection))
{
    command.Parameters.AddWithValue("@Name", theName);
    command.Parameters.AddWithValue("@MinDate", DateTime.Today);
    
    ...
}


Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]
 
Share this answer
 
Comments
bahman01 26-Jan-17 11:59am    
But for sql this way is the best because visual studio knows how to convert. It is better than changing characters manually.
Thank you Richard!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900