简体   繁体   中英

C# string with multiple double quotes & "/" slashes

I have a string like this

'Name.ToLower().Contains ("") And Created < ("05/12/2022 01:41:16") And Disabled == false'

How to deal with this in C#?

I've tried prepending with @""" etc.

dotnet fiddle

var a = @"'Name.ToLower().Contains ("""") And Created < (""05/12/2022"") And ExpandOnStart == false'";

像这样?

Obviously you have to escape special characters somehow. In older C# use verbatim strings : https://dotnetfiddle.net/8OtiKP

@"'Name.ToLower().Contains ("""") And Created < (""05/12/2022"") And ExpandOnStart == false'"

As you can see, " still needs to be escaped with "" , but all the other characters, including \ can be left as-is

In C#11 there's a better solution: raw string literal where there's no need to escape " at all

"""'Name.ToLower().Contains ("") And Created < ("05/12/2022 01:41:16") And Disabled == false'"""

This is a bit different approach, but you mentioned that the string is created by appending other strings, so possibly it'll help.

var createdDate = "05/12/2022";
var name = "some name";
var expandOnStart = "false";

var theString = $"Name.ToLower().Contains(\"{name}\") And Created < (\"{createdDate}\") And ExpandOnStart == \"{expandOnStart}\"";

// theString = Name.ToLower().Contains("some name") And Created < ("05/12/2022") And ExpandOnStart == "false"

https://dotnetfiddle.net/oq3UYq

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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