Following strings are samples.Strings are coming from response of api.
string s = "string contain another string(< a href =\"https:")";
string text = "This is a \"string\" in C#.";
string text1 = "This is a \na test \nb.";
I want to replace "" with "\" as I want to pass this value to Postgresql.
Only one backslash is not working in postgresql even if column has same value. It worked for double slash '\' or tripple slash'\' from pgadmin or azure data studio.
I am using linq from C# to connect with postgresql.
How to do that
Here in first/second string to introduce string inside string use '' for double quote
-- this code woked fine.
if (s.Contains("\""))
{
s = s.Replace("\"", "\\\"");
}
-- It is not working
if (s.Contains("\n"))
{
s = s.Replace("\n", "\\\n");
}
where is I am wrong.
It replace this string ("This is a \na test \nb.";
) to ("This is a \\\na test \\\nb.";
)
From C# not getting value but when same string I copy and pasted in pgadmin with like statement ,it is working.
var result = (from t in DbTestContext.Test
where t.TestName.Trim().ToLower().Contains(S.Trim().ToLower())
select new
{
TestStartDate = t.TestStartDate,
}).FirstOrDefault();
CodePudding user response:
You are wrong where you try to insert a line feed \n
into the SQL string. You don't need an actual linefeed there but a backslash flowed by the letter n
. So, write:
s = s.Replace("\n", "\\n");
In the first string "\n"
there is a "real" linefeed.
The second string is backslash 'n' in C#. PostgreSQL will interprete this as line feed.