2012-01-31 13 views
9

Duplicar posibles:
How to escape brackets in a format string in .Net
string.format format string containing {cómo agregar {en la cadena de formato C#

yo estaba tratando de cadena de formato como este, {Enum.Enum1, "Enum1String" } Intenté este código

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)); 

      } 

pero no funciona. Cómo agregar {en formato de cadena. Estoy pensando en utilizar stringbuilder.

+0

Excelente funcionó. Gracias –

Respuesta

26

De esta MSDN FAQ:

string s = String.Format("{{ hello to all }}"); 
Console.WriteLine(s); //prints '{ hello to all }' 
0

alternativa, usando el operador @ asegura que la cadena está representado tal y como aparece en el código:

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) + @"}"); 
} 
+1

El operador @ no cambiará la forma en que string.format maneja "{" y "}". Moverlos fuera de string.format evita el problema, sí, pero en realidad * no lo resuelve. – Servy

Cuestiones relacionadas