Reputation: 165
I am trying to use string.format to fill some values in a string template, below is the string value:
{
\"version\":\"9.40.20153.0\",\"sheetCount\":1,
\"sheets\":{
\"{0}\":
{
\"name\":\"{1}\",
\"rowCount\":{2},
\"columnCount\":{3},
\"colHeaderData\":{
\"dataTable\":{
{4}
}
},
\"data\":{
\"dataTable\":{
{5}
},
\"index\":0
}
}
}
And below is the code for calling the string.Format method:
string newString=SB.AppendLine(string.Format(genericTemplate, sheetName,columnCount, rowCount,3,5,6)).ToString();
It has become quite frustrating now :(. Please Help!!
Upvotes: 0
Views: 775
Reputation: 51
You have to escape all the curly brackets that are not used for formatting. This is done by simply duplicating each curly bracket.
For example the first line and last line should look like this:
{{
}}
while this line has to remain as it is:
\"{0}\":
var genericTemplate = @"
{{
""version"":""9.40.20153.0"",""sheetCount"":1,
""sheets"":{{
""{0}"":
{{
""name"":""{1}"",
""rowCount"":{2},
""columnCount"":{3},
""colHeaderData"":{{
""dataTable"":{{
{4}
}}
}},
""data"":{{
""dataTable"":{{
{5}
}},
""index"":0
}}
}}
}}";
var newString = string.Format(genericTemplate, "arg1", "arg2", "arg3", "arg4", "arg5", "arg6");
Upvotes: 2
Reputation: 1587
This is happening because you are trying to use curly braces in the string. You need to escape those as another answer has stated. Your better option may be to create an object for this and serialize it to JSON.
Upvotes: 0