-1

I am trying to write a string to a file using C#, the output i am looking for should be like this

<meta name="geo.region" content="Asia"/>

to achieve this i have tried this code,

writer.WriteLine(@"<meta name=""geo.region"" content="""+MetaTags.Region+"""/>");

but the output is,

<meta name="geo.region" content="Asia/>

No double quotes after "Asia"

I have also tried

 writer.WriteLine(@"<meta name=""geo.region"" content="""+MetaTags.Region+"""/>");

but it shows a syntax error

Asim Javaid
  • 537
  • 1
  • 5
  • 10

2 Answers2

4

In order to use two double-quotes to produce a double-quote in the result, the string literal needs to be prepended with @. So this is a syntax error:

"""/>"

But this isn't:

@"""/>"

Simply add the @ to your string literal as you already do for your other string literal:

writer.WriteLine(@"<meta name=""geo.region"" content=""" + MetaTags.Region + @"""/>");

Alternativly, if this is a recent enough version of C#, you can clean it up a little with string interpolation:

writer.WriteLine($"<meta name=\"geo.region\" content=\"{MetaTags.Region}\"/>");

If you prefer back-slashes to double-double-quotes that is.

David
  • 208,112
  • 36
  • 198
  • 279
1

In C# you can use a backslash before a double quote instead of doubling it:

writer.WriteLine("<meta name=\"geo.region\" content=\"" + MetaTags.Region + "\"/>");

Using string interpolation:

writer.WriteLine($"<meta name=\"geo.region\" content=\"{MetaTags.Region}\"/>");

It will output:

<meta name="geo.region" content="region"/>

More details:

Strings (C# Programming Guide)

String interpolation in C#

  • Not that this question needed any new answers, given that it's an obvious duplicate. But I think you mean "backslash", not "backspace". – Peter Duniho Jan 05 '21 at 20:25