9

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
  • 22,702
  • 6
  • 67
  • 85
riad
  • 6,906
  • 22
  • 56
  • 69
  • 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

24

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
  • 666,277
  • 106
  • 705
  • 986
  • 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://docs.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

Binary Worrier
  • 49,396
  • 18
  • 139
  • 181
  • 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'?>");