简体   繁体   English

在C#中查找特定的单引号并将其替换为双引号

[英]Finding a specific single quote and replacing with double quotes in C#

I've a problem where I want to replace some specific single quotes with double quotes inside a SQL string but not all singles quotes in that string. 我有一个问题,我想用SQL字符串中的双引号替换某些特定的单引号,而不是该字符串中的所有单引号。

EXEC procedureName 'param'eter1', 'parameter2'

In above example I just want to replace the singles quotes inside the 'param'eter1' but the singles quotes in start and end of the parameter to remain same. 在上面的示例中,我只想替换'param'eter1'内部的单引号,但参数开头和结尾的单引号保持不变。

Using below command replace all singles quotes in the string and it looks like this ''param''eter1'' which is not correct. 使用下面的命令替换字符串中的所有单引号,它看起来像这样的“ param” eter1”,这是不正确的。

sometext.Replace("'", "''")

I want it to look like this: 我希望它看起来像这样:

EXEC procedureName 'param''eter1', 'parameter2'

Also please note that I am already aware that using SqlParameter is a better solution to handle the single quotes in SQL parameters but due to the restrictions in the project environment I am unable to implement that. 还请注意,我已经知道使用SqlParameter是处理SQL参数中单引号的更好解决方案,但是由于项目环境中的限制,我无法实现这一点。

Update: 更新:

Changing the individual parameters before using them to construct the full statement is not an option for me as I don't have access to that code. 对于我来说,在使用单个参数来构造完整语句之前更改单个参数不是我的选择,因为我无法访问该代码。 My project works like a data layer where it received SQL strings from other applications to process. 我的项目就像一个数据层,在其中它从其他应用程序接收SQL字符串进行处理。

This is a very bad idea. 这是一个非常糟糕的主意。 The SQL syntax requires you to escape single quotes in literals exactly because it can otherwise not tell whether the single quote is meant to represent a single quote or meant to terminate the string literal. SQL语法要求您完全按原义对单引号进行转义,因为否则它无法分辨单引号是表示单引号还是终止字符串。

Consider the following example: 考虑以下示例:

EXEC procedureName 'param ', ' eter1', 'parameter2'

How would you know whether this is meant to have three parameters for the procedure call or only two? 您怎么知道这意味着该过程调用具有三个参数还是只有两个? And even if you knew that this specific procedure takes two parameters, you couldn't decide whether the middle part belongs to the first or second parameter. 而且,即使您知道此特定过程有两个参数,也无法确定中间部分属于第一个还是第二个参数。

If the system constructs sql statements from user input without dealing with single quotes before the full statement is constructed, this can be used very easily to attack the system via an sql injection . 如果系统在构造完整语句之前从用户输入构造sql语句而不处理单引号,则可以很容易地通过sql注入轻松使用它来攻击系统。

you can do like this 你可以这样

var aStringBuilder = new StringBuilder(theString);
aStringBuilder.Remove(3, 2); // just find a position of single quotes 
aStringBuilder.Insert(3, "/""); // replace that position with " quotes using loop
theString = aStringBuilder.ToString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM