10

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#?

Zach Johnson
  • 23,678
  • 6
  • 69
  • 86
riad
  • 7,144
  • 22
  • 59
  • 70
  • 2
    If you are creating XML then you shouldn't use a text writer like that. Use an `XmlWriter` instead to generate the XML correctly. – Dirk Vollmar May 26 '10 at 08:21

3 Answers3

26

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""?>");
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 2
    The second form (@-delimited string) is called a verbatim string literal https://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx – BlackTigerX Feb 17 '16 at 21:47
  • That documentation link has been retired, try [this one](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/string). – Scott Martin Nov 01 '18 at 16:09
9

Try

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

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

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Binary Worrier
  • 50,774
  • 20
  • 136
  • 184
  • Thanks, you really should 'accept' answers, in this case mine or Guffas, they are both correct :) – Binary Worrier May 26 '10 at 08:33
  • yes both of you r right.but some times i was too busy..to do it..i really sorry for that..thanks for remind me.. – riad May 26 '10 at 08:36
3

Since to XML both " and ' can used, try

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