How can I put quotes in a string?

2020-01-29 01:14发布

I need to write a string literal to a text file, but the C# compiler finds errors when I use quote characters in it.

My current code:

writeText.WriteLine("<?xml version="1.0" encoding="utf-8"?>");

I need the output for the text file to be:

<?xml version="1.0" encoding="utf-8"?>

How can I put quote characters in strings in C#?

标签: c# string quotes
3条回答
放荡不羁爱自由
2楼-- · 2020-01-29 01:55

You need to escape the quotation marks to put them in a string. There is two ways of doing this. Using backslashes in a regular string:

writeText.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");

Using double quoation marks in a @-delimited string:

writeText.WriteLine(@"<?xml version=""1.0"" encoding=""utf-8""?>");
查看更多
唯我独甜
3楼-- · 2020-01-29 01:57

Try

writeText.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");

Have a look at "What character escape sequences are available?" of the C# FAQ

查看更多
贼婆χ
4楼-- · 2020-01-29 01:59

Since to XML both " and ' can used, try

writeText.WriteLine("<?xml version='1.0' encoding='utf-8'?>");
查看更多
登录 后发表回答