13

Possible Duplicate:
How to escape brackets in a format string in .Net
string.format format string containing {

I was trying to format string like this, {Enum.Enum1,"Enum1String"} I tried this code

foreach (KeyValuePair<int, string> p in Helper.Dict)
            {
               // file.WriteLine(string.Format("{0} | {1}",p.Key,p.Value));
               file.WriteLine(string.Format("{Enum.{0},\"{1}\"}", p.Value,p.Value));

            }

but it doesn not work. How to add { in string format. I am thinking to use stringbuilder.

Community
  • 1
  • 1
L.E.
  • 646
  • 2
  • 8
  • 21

3 Answers3

29

From this MSDN FAQ:

string s = String.Format("{{ hello to all }}");
Console.WriteLine(s);    //prints '{ hello to all }'
M.Babcock
  • 18,753
  • 6
  • 54
  • 84
2
string t = "1, 2, 3";
string v = String.Format(" foo {{{0}}}", t); 

See duplicate post here How to escape braces (curly brackets) in a format string in .NET

using {{ and }} with result in { and } in String.Format.

Community
  • 1
  • 1
corylulu
  • 3,449
  • 1
  • 19
  • 35
0

Alternatively, using the @ operator ensures that the string is represented exactly as it appears in code:

foreach (KeyValuePair<int, string> p in Helper.Dict)
{
       // file.WriteLine(string.Format("{0} | {1}",p.Key,p.Value));
       file.WriteLine(@"{" + string.Format("Enum.{0},\"{1}\"", p.Value,p.Value) + @"}");
}
Michael Kingsmill
  • 1,815
  • 3
  • 22
  • 31
  • 1
    The @ operator won't change how string.format handles "{" and "}". Moving them outside of string.format does avoid the problem, yes, but it doesn't actually *solve* it. – Servy Jan 31 '12 at 17:56